What is the basic concept behind WaitHandle?

前端 未结 5 1850
清歌不尽
清歌不尽 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:56

    WaitHandle is an abstract base class for the two commonly used event handles: AutoResetEvent and ManualResetEvent.

    Both of these classes allow one thread to "signal" one or more other threads. They're used to synchronize (or serialize activity) between threads. This is accomplished using the Set and WaitOne (or WaitAll) methods. For example:

    Thread 1:

    // do setup work
    
    myWaitHandle.Set();
    

    Thread 2:

    // do setup work
    
    myWaitHandle.WaitOne();
    
    // this code will not continue until after the call to `Set` 
    // in thread 1 completes.
    

    This is a very rudimentary example, and there are loads of them available on the web. The basic idea is that WaitOne is used to wait for a signal from another thread that indicates that something has happened. In the case of AsyncWaitHandle (which is returned from invoking a delegate asynchronously), WaitOne allows you to cause the current thread to wait until the async operation has completed.

    When an AutoResetEvent or ManualResetEvent are not set, calls to WaitOne will block the calling thread until Set is called. These two classes differ only in that AutoResetEvent "unsets" the event once a successful call to WaitOne completes, making subsequent calls block again until Set is called. ManualResetEvent must be "unset" explicitly by calling Reset.

    WaitAll and WaitAny are static methods on the WaitHandle class that allow you to specify an array of WaitHandles to wait on. WaitAll will block until all of the supplied handles are Set, whereas WaitAny will only block until one of them gets Set.

提交回复
热议问题