What is the basic concept behind WaitHandle?

前端 未结 5 1862
清歌不尽
清歌不尽 2020-12-04 14:04

What is the basic concept behind WaitHandle in C# .net threading? Whats is its use? When to use it? What is the use of WaitAll and Wait

5条回答
  •  没有蜡笔的小新
    2020-12-04 14:45

    Imagine you have an array with 1000 items in it. You need to do some processing on every one of those items. This work will take some time, but is not I/O bound.

    For example, maybe you need to use each item to make a low-bandwidth web request. You have plenty of throughput to request many items at the same time, and the latency in each web request means doing one at a time could take longer than you want.

    Enter the world of parallel programming. Today there are a number of ways you can handle this task, and WaitHandle is a fundamental part of it. Even if you don't use a WaitHandle directly, whatever option you choose is likely relying on a WaitHandle such as WaitAll or WaitAny behind the scenes.

    Continuing the example, let's say you have a typical four-core CPU. In this situation, it doesn't make a lot of sense to have more than 4 threads going at once.* So 4 threads, but 1000 items; what do you do?

    One option uses WaitAny. You kick off 4 threads, and every time the WaitAny method returns you kick off another, until all 1000 items are queued. Note this is a poor example for WaitAny, because we know how many items there in total and can access any of the items at the same rate. WaitAny is best when you only have sequential access. There are other, similar situations where WaitAny can make a lot of sense.

    Another option uses WaitAll. Instead of queuing one item at a time, you set up one thread for each of the four cores assign it a different 250 item segment of the array. With this option, you can use WaitAll to wait for all the processing to finish.


    * Actually, it does. There's usually a certain amount of I/O time where the CPU would be idle, such that you can do better by having more than one thread going per core. But that's a story for another time.

提交回复
热议问题