Search code examples
c#backgroundworkerdetectionstalled

Detect a stalled BackgroundWorker in C#


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,


Solution

  • 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)