开发者

Best Way to wake a thread up to quit? C#

开发者 https://www.devze.com 2022-12-17 08:38 出处:网络
I spawn a thread (only one) to do some work and it pretty much takes care of itself not accessing any data outside of the tread except calling开发者_开发百科 callback() to see if the user wants to qui

I spawn a thread (only one) to do some work and it pretty much takes care of itself not accessing any data outside of the tread except calling开发者_开发百科 callback() to see if the user wants to quit (also sends a status report back to the main thread to display in the GUI).

When the close closes the exe i would like to wake up the thread and have it quit, whats the best way of doing this? The callback already says if the user wants to quit so now the issue is using Thread.Sleep and waking it up prematurely so it can quit instead of having the process live for another few seconds or minutes. This feature would be nice for stop to exit more quickly.


Another approach would be as follows:

Have a ManualResetEvent in your program and call Set when you want the thread to finish up and close down. Instead of calling Thread.Sleep on your work thread, call event.WaitOne and pass in a TimeSpan object. If the event is signalled, your worker thread will wake up before the timeout occurs - WaitOne will return true.


Use a BackgroundWorker or set your thread's IsBackground property to true, then it won't keep your application open.

I'd recommend the BackgroundWorker, but the latter is a quick fix.

Update

Original poster changed his requirements after posting the question (see comments attached to this question). Update to answer follows:

If you want to stop a background operation without ending the application, please see Background worker's CancelAsync method. Also, don't use Thread.Sleep - use a WaitHandle and call WaitOne on what you need to wait for.


I have to agree with Mark. The only thing clear about your question is that you need to reexamine your threading strategy. You say you have a thread doing work but then you say you want to wake it up?

Is the thread waiting for work? If so, sleep in shorter cycles and check for exit more often or use a reset event. The best way to wake a thread up is to not put it to sleep. Do what you have to do and exit. Always check for interrupt signals, in whatever form you implement them, before starting any long running operations, and again, if you must sleep the thread, do it in short cycles.

Is the thread busy and you want to interrupt it? You may have no choice but to kill it if you cannot instrument it such that it can respond to interrupt signals in a timely fashion.

0

精彩评论

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