Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Co-ordinating worker thread shutdown

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.

  • Add a State property to IWorker. Should work but I'm going to be polling states which seems a little nasty.
  • Make the shutdown command blocking - Would probably be my ideal solution but I'm not sure how to implement it - does the worker Sunclock a private object which Shutdown() should also try to Synclock after setting the flag?
  • Something else?

Any articles, advice or suggestions appreciated. Examples in C# or VB are fine.

like image 864
Basic Avatar asked Aug 27 '26 02:08

Basic


1 Answers

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
like image 140
Reed Copsey Avatar answered Aug 29 '26 19:08

Reed Copsey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!