开发者

Using a queue in a multithreaded situation in C#

开发者 https://www.devze.com 2023-01-04 21:23 出处:网络
I just learned about queues in 开发者_Python百科.NET and I have a few questions. Let\'s say that I\'m building an application that downloads the HTML of pages and then processes it. Here\'s how I wan

I just learned about queues in 开发者_Python百科.NET and I have a few questions.

Let's say that I'm building an application that downloads the HTML of pages and then processes it. Here's how I want it to operate:

  1. A main thread adds URLs to a queue
  2. This queue is read by two other threads. They "dequeue" a URL and then download the corresponding HTML.
  3. The HTML is then sent back to the main thread.
  4. When the HTML arrives in the main thread, it is placed into another queue, handled by another two threads. These threads process the HTML.
  5. The results of the processing are returned to the main thread.

How can I implement such a scenario without the possibility of a race condition?

Also, what is the best way to pass the information between queues and threads as described above?

Could you give me some sample code?

Thanks!


I recommend BlockingCollection<T>. It represents a "producer/consumer queue" common in multithreading.


There are two ways that come to mind.

The first is to use a collection that implements locking to produce thread safe consistency (such as BlockingCollection as mentioned elsewhere).

The second is to use an immutable collection (such as the ones described by Eric Lippart in Link ) which avoids most of the hassle of thread locking and race conditions in the first place and makes what's ever left over a little more obvious usually.

0

精彩评论

暂无评论...
验证码 换一张
取 消