2

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?

6
  • If you are going to need it again then why disposing it ? Jun 2, 2012 at 15:01
  • why do you want to use a background worker? A timer seems more appropriate to trigger an operation based on an interval Jun 2, 2012 at 15:03
  • @Aybe: My concern was that the timer should run unlimited times i.e after every 30 second or so until the windows service that I am using this in closes. So, where do I dispose this? Jun 2, 2012 at 15:03
  • @BrokenGlass: Here's my previous post from which I decided to use Background worker instead of the main thread. stackoverflow.com/questions/10793278/… Jun 2, 2012 at 15:04
  • possible duplicate of Proper way to Dispose of a BackGroundWorker Jun 2, 2012 at 15:13

1 Answer 1

3

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.

3
  • Creating a new thread for each background timer_elapsed looked like an overkill to me, but I think it's fine if the resources held are very low. Jun 2, 2012 at 15:12
  • As Henk mentioned, you aren't actually creating threads (usually), just borrowing them from a thread pool.
    – Mark M
    Jun 2, 2012 at 15:15
  • HenkHolterman, For anyone that sees this. Your comment is probably unintentionally misleading. The backgroundworker runs operations on another thread but only when called. Jun 19, 2018 at 16:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.