성태의 닷넷 이야기
홈 주인
모아 놓은 자료
프로그래밍
질문/답변
사용자 관리
사용자
메뉴
아티클
외부 아티클
유용한 코드
온라인 기능
MathJax 입력기
최근 덧글
[정성태] Java - How to use the Foreign Funct...
[정성태] 제가 큰 실수를 했군요. ^^; Delegate를 통한 Bein...
[정성태] Working with Rust Libraries from C#...
[정성태] Detecting blocking calls using asyn...
[정성태] 아쉽게도, 커뮤니티는 아니고 개인 블로그입니다. ^^
[정성태] 질문이 잘 이해가 안 됩니다. 우선, 해당 소스코드에서 ILis...
[양승조
] var대신 dinamic으로 선언해서 해결은 했습니다. 맞는 해...
[양승조
] 또 막혔습니다. ㅠㅠ var list = props[i].Ge...
[양승조
] 아. 감사합니다. 어제는 안됐던것 같은데....정신을 차려야겠네...
[정성태] "props[i].GetValue(props[i])" 코드에서 ...
글쓰기
제목
이름
암호
전자우편
HTML
홈페이지
유형
제니퍼 .NET
닷넷
COM 개체 관련
스크립트
VC++
VS.NET IDE
Windows
Team Foundation Server
디버깅 기술
오류 유형
개발 환경 구성
웹
기타
Linux
Java
DDK
Math
Phone
Graphics
사물인터넷
부모글 보이기/감추기
내용
<div style='display: inline'> <h1 style='font-family: Malgun Gothic, Consolas; font-size: 20pt; color: #006699; text-align: center; font-weight: bold'>C# - Collection 개체의 다중 스레드 접근 시 "Operations that change non-concurrent collections must have exclusive access" 예외 발생</h1> <p> 다음과 같은 Q&A가 있는데,<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > HttpClient 에러? ; <a target='tab' href='https://forum.dotnetdev.kr/t/httpclient/1464/2'>https://forum.dotnetdev.kr/t/httpclient/1464/2</a> </pre> <br /> 정리해 보면, EF 사용 코드에 대한 단위 테스트를 했는데 이런 오류가 발생했다는 것입니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > System.InvalidOperationException: Operations that change non-concurrent collections must have exclusive access. A concurrent update was performed on this collection and corrupted its state. The collection's state is no longer correct. </pre> <br /> 구체적인 것은 오류 메시지의 (함께 질문에 올렸으면 좋았을) call stack을 봐야 이것이 ORM 관련 코드에서 발생한 것인지, 단순히 Collection의 동기화 문제로 발생한 것인지 판단할 수 있습니다. 하지만, 아마도 이것은 대체로 Collection의 동기화 문제일 가능성이 있습니다.<br /> <br /> 실제로 이에 대한 재현 코드를 다음의 예제로 가능합니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > using System.Collections.Generic; using System.Threading.Tasks; class Program { static async Task Main(string[] args) { Dictionary<int, int> dict = new Dictionary<int, int>(<span style='color: blue; font-weight: bold'>1000000</span>); List<Task> tasks = new List<Task>(); for (int i = 0; i < 2; i++) { Task task = <span style='color: blue; font-weight: bold'>Task.Run</span>(() => { for (int j = 0; <span style='color: blue; font-weight: bold'>j < 1000000</span>; j++) { <span style='color: blue; font-weight: bold'>dict[j] = j;</span> } }); tasks.Add(task); } await Task.WhenAll(tasks); } } </pre> <br /> 스레드 2개로 Dictionary에 값을 할당하고 있는데요, 이로 인해 다음과 같은 예외가 발생합니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > Unhandled exception. System.InvalidOperationException: Operations that change non-concurrent collections must have exclusive access. A concurrent update was performed on this collection and corrupted its state. The collection's state is no longer correct. at System.Collections.Generic.Dictionary`2.TryInsert(TKey key, TValue value, InsertionBehavior behavior) at System.Collections.Generic.Dictionary`2.set_Item(TKey key, TValue value) at ConsoleApp1.Program.<>c__DisplayClass0_0.<Main>b__0() at System.Threading.Tasks.Task.InnerInvoke() at System.Threading.Tasks.Task.<>c.<.cctor>b__277_0(Object obj) at System.Threading.ExecutionContext.RunFromThreadPoolDispatchLoop(Thread threadPoolThread, ExecutionContext executionContext, ContextCallback callback, Object state) --- End of stack trace from previous location --- at System.Threading.ExecutionContext.RunFromThreadPoolDispatchLoop(Thread threadPoolThread, ExecutionContext executionContext, ContextCallback callback, Object state) at System.Threading.Tasks.Task.ExecuteWithThreadLocal(Task& currentTaskSlot, Thread threadPoolThread) --- End of stack trace from previous location --- at ConsoleApp1.Program.Main(String[] args) at ConsoleApp1.Program.<Main>(String[] args) </pre> <br /> 오류 내용이 정확히 같습니다. ^^<br /> <br /> <hr style='width: 50%' /><br /> <br /> 재미있는 것은, 위의 코드에서 컬렉션에 대한 초기 크기를 지정하지 않으면,<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > Dictionary<int, int> dict = new Dictionary<int, int>(<span style='color: blue; font-weight: bold'>/* 1000000 */</span>); </pre> <br /> (가끔 System.InvalidOperationException이 발생하기는 하지만) 예외가 주로 다음과 같이 발생합니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > Unhandled exception. System.ArgumentException: Destination array was not long enough. Check the destination index, length, and the array's lower bounds. (Parameter 'destinationArray') at System.Array.Copy(Array sourceArray, Int32 sourceIndex, Array destinationArray, Int32 destinationIndex, Int32 length, Boolean reliable) at System.Array.Copy(Array sourceArray, Array destinationArray, Int32 length) at System.Collections.Generic.Dictionary`2.Resize(Int32 newSize, Boolean forceNewHashCodes) at System.Collections.Generic.Dictionary`2.TryInsert(TKey key, TValue value, InsertionBehavior behavior) at System.Collections.Generic.Dictionary`2.set_Item(TKey key, TValue value) at ConsoleApp1.Program.<>c__DisplayClass0_0.<Main>b__0() at System.Threading.Tasks.Task.InnerInvoke() at System.Threading.Tasks.Task.<>c.<.cctor>b__277_0(Object obj) at System.Threading.ExecutionContext.RunFromThreadPoolDispatchLoop(Thread threadPoolThread, ExecutionContext executionContext, ContextCallback callback, Object state) --- End of stack trace from previous location --- at System.Threading.ExecutionContext.RunFromThreadPoolDispatchLoop(Thread threadPoolThread, ExecutionContext executionContext, ContextCallback callback, Object state) at System.Threading.Tasks.Task.ExecuteWithThreadLocal(Task& currentTaskSlot, Thread threadPoolThread) --- End of stack trace from previous location --- at ConsoleApp1.Program.Main(String[] args) at ConsoleApp1.Program.<Main>(String[] args) </pre> <br /> 결국 저 오류도 컬렉션의 스레드 동기화를 제대로 하지 못했을 때 발생할 수 있는 것입니다. 그런데, 한 가지 의문인 점이 있습니다. 아마 EF에서도 역시 초기 크기를 지정하지 않았을 것이고, 그렇다면 확률적으로 System.ArgumentException 예외가 더 많이 발생했을 텐데 질문한 사람은 System.InvalidOperationException 예외 메시지를 봤던 것입니다.<br /> <br /> 우연치고는 상당히 절묘한데, 제가 테스트한 코드 외의 어떤 조건에서는 System.InvalidOperationException 예외가 고정적으로 나오는 상황도 있는 듯합니다.<br /> <br /> <hr style='width: 50%' /><br /> <br /> 참고로, 다음의 글도 한번 읽어 보시길 권합니다. ^^<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > IEnumerator는 언제나 읽기 전용일까? ; <a target='tab' href='https://www.sysnet.pe.kr/2/0/1308'>https://www.sysnet.pe.kr/2/0/1308</a> DataContext가 thread-safe한 것인가? ; <a target='tab' href='https://www.sysnet.pe.kr/2/0/855'>https://www.sysnet.pe.kr/2/0/855</a> </pre> </p><br /> <br /><hr /><span style='color: Maroon'>[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]</span> </div>
첨부파일
스팸 방지용 인증 번호
1561
(왼쪽의 숫자를 입력해야 합니다.)