I think you need to do periodic work in thread repeated from time to time. You can do it!
First of all, you should use a thread only once. Create just one thread only once in the very beginning. Start it, only once, for example, on the
Form.Shown
event.
Now the thread should contain an infinite look waiting for your command in the very beginning of each cycle. Don't use spin wait. You should only use thread synchronization primitives. For your purpose, use
System.Threading.EventWaitHandle
,
System.Threading.AutoResetEvent
or
System.Threading.ManualResetEvent
. When you call its
Set
method (and thread was sleeping at the call to its
WaitOne
method), the thread get awaken and do your task. You also need a mechanism to pass a task to the thread.
You can find even create a blocking message queues to feed task data to the thread. You can fined the most "packaged" ready-to-use solution from my Tip/Tricks article:
Simple Blocking Queue for Thread Communication and Inter-thread Invocation[
^] (See also "alternative" (not really alternative, same thing, but the using available queue) answer for Framework v.4.0.).
In the body of your thread, you can notify your UI to update/visualize you status, results, etc. Only remember, from the thread, you cannot use UI controls directly. Instead, you should use
Control.Invoke
. With
Invoke
, you don't really call the delegate on the thread calling
Invoke
. Instead, the delegate and call parameters are posted on some UI queue and later removed and called directly by UI thread.
By the way, my code referenced about can give you good idea on how the invocation mechanism is implemented in UI thread.
—SA