I've a question regarding thread handling in C#:
I have a master thread who creates a slave thread with
pollthread = new Thread(doPollThread);
pollthread.Start(this);
I have a
ManualResetEvent resetevent
the slave thread executes an endless loop like
private static void doPollThread(object thisObject){
SpeedCounterDevice sc = (SpeedCounterDevice) thisObject;
while (true) {
sc.resetevent.WaitOne();
//do some work ....
Thread.Sleep(400);
}
}
The purpose of the slave thread is to poll an external device through a network socket (how are you .. how are you ... get measurement result ... how are you ....)
but this socket is created in functions of the master thread
And I want to connect the socket through an UI-Button-Press, disconnect through the UI, connect again, .... in the master thread
So control of the socket should belong to the master thread, only the actual data transfer over the network should be done by the slave
Now I want to suspend the slave thread in a function running in the master thread like
resetevent.Reset();
to disconnect the network connection later on when the slave loop is finished
But then I want to wait in the master thread (block it) until the slave thread executed WaitOne(), but without any possibility to come into a deadlock or something else problematic ...
(I want to finish the loop without interrupt it)
Yes, you can create another ResetEvent, block the master thread, but if the slave is getting the resetEvent right between signalling the master thread and executing WaitOne(), he will sleep but will not wake up the master thread ...
Is there any safe nice way to solve this problem?
Thank you!
Regards, Hans Juergen
Copyright Notice:Content Author:「Funky」,Reproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/72600946/c-sharp-block-master-thread-until-slave-thread-executed-manualresetevent-waito