What is the correct way in C# to wait for one of these events, which comes first: an AutoResetEvent is set or another Thread is ended?
To wait for multiple wait handles can be used WaitHandle.WaitAny. But Thread is not WaitHandle.
Example:
class Example
{
AutoResetEvent _stopEvent = new AutoResetEvent(false);
public void Start()
{
var handles = new WaitHandle[] { _stopEvent, Thread.CurrentThread }; //error: Thread is not WaitHandle
var t = new Thread(() =>
{
//...
int r = WaitHandle.WaitAny(handles);
switch(r) {
case 0: Console.WriteLine("Stop called"); break;
case 1: Console.WriteLine("thread ended"); break;
}
//...
});
t.SetApartmentState(ApartmentState.STA);
t.Start();
}
public void Stop()
{
_stopEvent.Set();
}
}
Currently I use this workaround.
class Workaround
{
AutoResetEvent _stopEvent = new AutoResetEvent(false);
public void Start()
{
var stopEvent = _stopEvent;
var thread1 = Thread.CurrentThread;
var t = new Thread(() =>
{
//...
while(!stopEvent.WaitOne(100)) {
if(thread1.Join(0)) break;
}
//...
});
t.SetApartmentState(ApartmentState.STA);
t.Start();
}
public void Stop()
{
_stopEvent.Set();
}
}
I am aware about the native API - WaitForMultipleObjects etc, but would like to avoid it.
The code will be in a library; it cannot explicitly set event when the thread is ending.