Search code examples
c#asynchronousbackgroundworker

Disposing a background worker


Is it necessary to dispose off the Background Worker after I have done the processing work inside the DoWork event, or being a managed object this will automatically get disposed eventually?

Previously, I was performing some functions inside the timer_elapsed i.e to perform a task every thirty seconds. Now, I am doing the same processing inside the BackGround Worker's DoWork event. How do I loop this bgWorker event to be performed after every 30 seconds (say) bgworker.RunWorkerAsync();

If I put this bgWorker.RunWorkerAsync() indie timer_elapsed, how do I dispose it after every timer elapse?


Solution

  • Is it necessary to dispose off the Background Worker after ...

    No. The BackgroundWorker does implement the IDisposable interface but only as a blanket feature inherited from Component. It serves no purpose.

    If I put this bgWorker.RunWorkerAsync() in timer_elapsed

    Doubtful if you should do that at all. But if you do, just create a new Backgroundworker each time.

    A Backgroundworker is a relatively 'light' object, it holds no resources. The thread is borrowed from the ThreadPool.

    If you are a stickler for principal, you may call Dispose() on the old one before creating a new one. But it won't make much difference.