I have an example for cross-thread event signalling in C++.
HANDLE WriteCompleted = CreateEvent(NULL, FALSE, FALSE, NULL);
SetEvent(WriteCompleted);
WaitForSingleObject(pThis->WriteCompleted, INFINITE);
CloseHandle(WriteCompleted);
If SetEvent() sets the event, then what clears that event? Does WaitForSingleObject() clears this event on return?
What would be the approach to implement the same idea using C#?
The equivalent in C# can be accomplished with a ManualResetEvent
.
using(var WriteCompleted = new ManualResetEvent(false))
{
WriteCompleted.Set(); //causes threads blocked on WaitOne() to proceed
WriteCompleted.WaitOne(); //waits until the event is signaled
WriteCompleted.Reset(); //causes threads to block on WaitOne() call
}
You can also use AutoResetEvent
, which automatically calls Reset
after Set
. The event you created in your sample code sets bManualReset to FALSE
indicating that this event more closely emulates an AutoResetEvent
.
No matter how you end up implementing it, don't forget to call Dispose()
on the object at some point. Dispose()
is implicitly called in the sample when the using
block goes out of scope.
Here is a more concrete sample usage of AutoResetEvent:
private static AutoResetEvent m_event = new AutoResetEvent(false);
private static void Main(string[] args)
{
new Thread(() =>
{
m_event.WaitOne();
Console.WriteLine("Signal received from main");
}).Start();
Console.WriteLine("Sending signal");
Thread.Sleep(1000);
m_event.Set();
m_event.Dispose();
}
If you wanted to re-use the event, it is automatically reset to blocking after Set()
is called because we are using an AutoResetEvent
. With ManualResetEvent
you would need to call Reset()
in order to have it block threads again.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.