I've got a Windows Service that runs BackgroundWorker
's, and I'm wondering if I'm doing the right thing when I stop my Windows Service.
Is it enough to:
BackgroundWorker1_DoWork
method complete (I have a while loop in it now, doing some tasks) BackgroundWorker
, to null
Is there some kind of Dispose()
method I need to call (In the same way the Timer
class has Timer.Dispose();
)?
Frankly, when you stop your windows service - it really doesn't matter. Your win32 process is terminated, so its not strictly necessary to clean up your IDisposables. Any unmanaged resources will have a finalizer that will still run.
That said, it's normal to have a class level background worker that gets disposed when e service class does. Not necessary, but it's always good to be clean.
Since BackgroundWorker
implements IDisposable
, you should be disposing it when you are finished with it.
You mention that this is in a Windows service so there are a few things that come into play here. When you stop a Windows service, you get around 30 seconds to return from the OnStop
method in your ServiceBase
implementation. If you do not return within this time, Windows reports to the user that it could not stop the service. What you should do is signal to the BackgroundWorker
that you need it to stop (using the CancelAsync
mechanism), dispose of the worker, and then exit. However, since you are stopping the service, it doesn't really matter as the whole process will be terminated anyway, including any threads that are running within it.
If you were to do as you say and wait for the worker to complete (in the OnStop
method), your service may appear to the user as if it has hung as Windows will say that it cannot stop it, and the process will still be running.
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