开发者

Stopping Thread in C# while is in Unlimited wait mode

开发者 https://www.devze.com 2023-03-14 15:18 出处:网络
All, I have a main thread which creates 10 threads all executing same method. Inside this method there is a connect开发者_Go百科ion to a message queue and each thread waits unlimited until a message

All,

I have a main thread which creates 10 threads all executing same method. Inside this method there is a connect开发者_Go百科ion to a message queue and each thread waits unlimited until a message arrives. However I need to have the functionality to tell the thread to die if I wanted to. How can I do it ?

Here is an example:

void ExecuteThread(){
//run some stuff
//listen to a message queue
//Here wait unlimited until a message arrives
}

How do I notify the above code which is in the unlimited wait command to stop the thread? I can't just abort it as I would it to gracefully disconnect from the queue.

Many Thanks, MK

}


What sort of message queue? Can your main thread send a suicide message, (well, 10 suicide messages, or one suicide message with an internal count), on the queue?

Rgds, Martin


Do not wait unlimited, but use WaitOne with a timeout. Put that in a loop, which checks a flag for canceling. Then, from your main thread, you can signal threads to exit.

Something like (pseudo-code):

while (keepRunning)
{
   //wait 5 seconds for message
}


Usually you have to create a waiting loop, which checks a shared variable. This variable says if the thread has to cancel it's operation.

WARNING: Do not create an infinity loop which checks the variable to often, this causes "busy waiting". You should wait for a message in the queue until a timeout arrives. After that timeout you can check your control variable and enter the waiting process for the queue again.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号