C# Threading and Queues

后端 未结 5 1507
不知归路
不知归路 2021-02-02 01:13

This isn\'t about the different methods I could or should be using to utilize the queues in the best manner, rather something I have seen happening that makes no sense to me.

5条回答
  •  温柔的废话
    2021-02-02 01:38

    Here's a possible answer from the MSDN page on this topic:

    Enumerating through a collection is intrinsically not a thread-safe procedure. Even when a collection is synchronized, other threads can still modify the collection, which causes the enumerator to throw an exception. To guarantee thread safety during enumeration, you can either lock the collection during the entire enumeration or catch the exceptions resulting from changes made by other threads.

    My guess is that you're correct - at some point, there's a race condition happening, and you end up dequeuing something that isn't there.

    A Mutex or Monitor.Lock is probably appropriate here.

    Good luck!

提交回复
热议问题