Detect a stalled BackgroundWorker in C#

1k Views Asked by At

I use backgroundworker objects to preform some async and threading where needed. Every once in awhile when I run the backgroundworker it stalls in the middle of running and doesn't finish. It usually does this when I am running more then 1 backgroundworker at the same time.

What I want to do when it stalls is cancel the operation and re-run it. My problem is I don't know how to detect when it has stalled. Is there some code I need to add to "notify" that the worker has stalled or is there no way to know?

Thanks,

2

There are 2 best solutions below

3
On BEST ANSWER

You should debug your code and figure out why its stalling.

  • Do you have a multithreaded deadlock?
  • Are resource pools exhausted?
  • Are you waiting indefinitely on a network resource?
  • Is an exception thrown mid process?

BackgroundWorker provides the following callback:

  • DoWork, which is called before your work starts.
  • RunWorkerCompleted, which is called when your work is done.

You could extend this with a wrapper to log a warning if the action takes longer than a certain amount of time if you want to enforce some sort of service level for async actions. (Eg. start a timer when DoWork is called and when the timer elapses log the warning, clear timer when complete)

3
On

That depends entirely on what you mean by "stalled". If you have managed to deadlock the worker thread, then you'll need to find the problem and unpick the mess. If it is throwing an exception, then the RunWorkerCompleted event should fire, with a non-null Error in the event-args.