2012-03-02 3 views
4

Entity Framework를 사용하는 동안 동시성을 처리하는 가장 좋은 방법을 찾고 있습니다. http://msdn.microsoft.com/en-us/library/bb399228.aspx 을 그리고 그것은 다음과 같습니다 : 가장 간단하고 (또한 스택에) 권장 솔루션은 여기에 설명되어Entity Framework에서 동시 처리 처리

try 
{ 
    // Try to save changes, which may cause a conflict. 
    int num = context.SaveChanges(); 
    Console.WriteLine("No conflicts. " + 
    num.ToString() + " updates saved."); 
} 
catch (OptimisticConcurrencyException) 
{ 
    // Resolve the concurrency conflict by refreshing the 
    // object context before re-saving changes. 
    context.Refresh(RefreshMode.ClientWins, orders); 

    // Save changes. 
    context.SaveChanges(); 
    Console.WriteLine("OptimisticConcurrencyException " 
    + "handled and changes saved"); 
} 

그러나이 충분하다? Refresh()와 두 번째 SaveChanges() 사이에 무언가가 변경되면 어떻게 될까요? catch되지 않은 OptimisticConcurrencyException이 발생합니까?

편집 2 :

int savesCounter = 100; 
    Boolean saveSuccess = false; 
    while (!saveSuccess && savesCounter > 0) 
    { 
     savesCounter--; 
     try 
     { 
      // Try to save changes, which may cause a conflict. 
      int num = context.SaveChanges(); 
      saveSuccess = true; 
      Console.WriteLine("Save success. " + num.ToString() + " updates saved."); 
     } 
     catch (OptimisticConcurrencyException) 
     { 
      // Resolve the concurrency conflict by refreshing the 
      // object context before re-saving changes. 
      Console.WriteLine("OptimisticConcurrencyException, refreshing context."); 
      context.Refresh(RefreshMode.ClientWins, orders); 

     } 
    } 

내가 Iunderstand 새로 고침()가 어떻게 작동하는지 확실하지 않다 :

나는이 최종 해결책이 될 것이라고 생각합니다. 전체 컨텍스트를 새로 고 칩니 까? 그렇다면 추가 인수 (엔터티 개체)가 필요한 이유는 무엇입니까? 또는 지정된 객체 만 새로 고 칩니 까?

Order dbOrder = dbContext.Orders.Where(x => x.ID == orderID); 
dbOrder.Name = "new name"; 
//here whole the code written above to save changes 

그것이 dbOrder해야한다 : 새로 고침() 두 번째 인수로 전달해야하는지이 상황에서 예를 들어 ?

+2

+1 내가 처음이 기사를 읽었을 때와 똑같은 이의가 있었다. 일반적으로 예외 처리기에서 "위험한"작업 (saveChanges)을 수행하는 것은 바람직하지 않습니다. 공식 문서에서이 사실을보고 놀랐습니다. –

+1

다시 : 귀하의 변경, 그것은 좋아 보인다. 100 회 재시도가 상황을 해결하지 못한다고 말하는 경우 조심스럽게 루프를 돌파 할 수있는 방법을 강구 할 것입니다. 절대로 루프를 끝내지 않는 문제를 디버그하기가 어렵습니다. 그들은 결코 일어나지 않아도 되겠지만 ;-) –

+1

이 링크에서 접근 방법을 시도하십시오. 다음과 같이 더 신뢰할 수있는 동시성을 처리하는 다른 방법을 사용하십시오. - http://www.asp.net/mvc/tutorials/asp-net-mvc-application에서 엔티티 프레임 워크와 함께 동시 처리를 사용하여 ef-using-mvc/처리 동시 시작 –

답변

4

네, 두 번째 저장도 - Refresh()SaveChanges() 사이에서 변경되면 OptimisticConcurrencyException이 발생할 수 있습니다.

주어진 예제는 아주 간단한 재시도 논리 일 뿐이며, 두 번 이상 재 시도하거나 충돌을 더 복잡한 방법으로 해결해야하는 경우 중첩 시도보다 n 번 재 시도 할 루프를 만드는 것이 더 좋습니다. try/이 단일 레벨 이상을 포착하십시오.