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?

Adam
  • 15,537
  • 2
  • 42
  • 63
user1240679
  • 6,829
  • 17
  • 60
  • 89
  • If you are going to need it again then why disposing it ? – aybe Jun 02 '12 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 – BrokenGlass Jun 02 '12 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? – user1240679 Jun 02 '12 at 15:03
  • @BrokenGlass: Here's my previous post from which I decided to use `Background worker` instead of the main thread. http://stackoverflow.com/questions/10793278/implementing-a-waiting-routine-inside-a-timer-elapsed-event – user1240679 Jun 02 '12 at 15:04
  • possible duplicate of [Proper way to Dispose of a BackGroundWorker](http://stackoverflow.com/questions/2542326/proper-way-to-dispose-of-a-backgroundworker) – Hans Passant Jun 02 '12 at 15:13
  • After reading the linked question: you're better off with a timer and a little state-tracking logic: Does-it-run-now, Did-it-run-at-last-tick – H H Jun 02 '12 at 15:18

1 Answers1

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.

H H
  • 263,252
  • 30
  • 330
  • 514
  • 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. – user1240679 Jun 02 '12 at 15:12
  • As Henk mentioned, you aren't actually creating threads (usually), just borrowing them from a thread pool. – Mark M Jun 02 '12 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. – David Bentley Jun 19 '18 at 16:44