I've got a List(Of IWorker) which contains a number of concretes. IWorker in turn has a Startup() and Shutdown() method.
Inside the Worker class, Startup() creates a new worker thread then returns. Shutdown() presently sets a private ShutDownRequested flag and returns. The flag is checked by the worker thread (at worst every few seconds).
This all works fine but at present the parent app has no way to determine if the Worker has finished shutting down.
I can see a number of ways around this but am not sure what the best one is.
State property to IWorker. Should work but I'm going to be polling states which seems a little nasty.Sunclock a private object which Shutdown() should also try to Synclock after setting the flag?Any articles, advice or suggestions appreciated. Examples in C# or VB are fine.
I would not try to use locking to block on Shutdown(), if you want shutdown to be a blocking operation.
If you can use .NET 4, I would make your internal execute method a Task. You could then just call Task.Wait() to block until it's complete.
If you must use .NET 3.5 or earlier, I would have the Shutdown() call, internally, wait on a WaitHandle, such as a ManualResetEvent. The shutdown code could then look like:
' Include:
Private shutdownEvent as ManualResetEvent = new ManualResetEvent(false)
Sub Shutdown()
ShutDownRequested = True
shutdownEvent.WaitOne()
End Sub
The polling loop (thread operation) would then do:
Sub Execute()
While Not ShutDownRequested
' Do your work
End While
' Before you exit, "set" the event:
shutdownEvent.Set()
End Sub
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With