How to use waitHandle in vb.net
I have VS2010 and I'm working on a windows form application.
So, I have threads created dynamically (depending on user input), the processing for these threads can take quiet a while (days in extreme cases). So I've put a button on the form and want to be able to 'pause' or 'suspend' the threads. I've looked up the .suspend method and it has been replaced (I've tried using it but it does fail sometimes - causing the UI to crash) so the new method for doing this that I've found is 'waithandle'. I've read the documentation for this and I can't work out how to use it.
This is the basic structure of each of the threads:
Do 'time consuming operations loop 'a number of times
Then in a separate button I want to put the pause code. It's not all that important that it's paused quickly, pausing on the next run through the loop is fine (each run through is quite quick, it just does it hundreds of times). I'm assuming I have to put the waithandle check at the start of the loop but I don't actually know how to implement this. This is my waithandle dim code:
Dim waitHandles As System.Threading.EventWaitHandle = New System.Threading.AutoResetEvent(True)
All threads are to be paused at once (except the main UI thread) so I think that means I only need one wait handle but I'm not sure about this.
Anyway, if anyone can just tell me what code goes into the do loop and what goes into the pause button I think I can work through everything else. :)
Thanks! I got it working. Here's my implimentation:
Dim mre As New System.Threading.ManualResetEvent(True)
(that's at the top of the code (just under 'public class form 1') then in the threading it has:
finally in the button that pauses/unpauses the thread it has:
mre.Reset() 'to resume the threads and, mre.Set() 'to pause the threads
Use a ManualResetEvent for this. An AutoResetEvent is 'almost a semaphore' in that you would have to signal it as many times as you have threads that are waiting - this can become awkward under some circumstances.
Create the event signaled, (ie set), and wait on it in your threads at a suitable point where the system call to wait will have a negligible impact on the loops in your threads, ie. maybe not in an innermost loop.
Clear the event in your 'Pause' button OnClick(), set it in your 'Resume' OnClick().
Sorry, no actual code 'cos I don't have any VB, but it should be easy to do :)