Click here to Skip to main content
15,900,973 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
I am suing backgroundworker do some time consuming work and I want to cancel it if I don't want to wait long time until it finish.

in one of my dowork I can check the CancelationPending periodically, since I put it in for statement where in loop, but there is another situation.
let's say that I am going after a large amount of data from our system. In this case I can't periodically check CancelationPending.
Assuming the dowork is off doing its job for a very long time, how do you cancel the thread?
Posted

1 solution

You can't force the termination of a background worker, it simply isn't designed for that.

You have 3 options, in the order in which I would use them.

1) If you use .NET 4.0 you can use the TPL, Sacha Barber has written a series of articles on the subject.
Task Parallel Library: 1 of n[^]

2) You can use the good old System.Threading.Thread
Threading Tutorial (X#)[^]

3) You can get the get the Thread the BackgroundWorker is running on in the DoWork event save it in a field and you can then abort the thread.
C#
private Thread _backgroundWorkerThread;

public void StartBackgroundWorker()
{
    BackgroundWorker backgroundWorker = new BackgroundWorker();
    backgroundWorker.DoWork += DoWork;
    backgroundWorker.RunWorkerAsync();
}

public void AbortBackgroundWorker()
{
    if(_backgroundWorkerThread != null)
        _backgroundWorkerThread.Abort();
}

void DoWork(object sender, DoWorkEventArgs e)
{
    try
    {
        _backgroundWorkerThread = Thread.CurrentThread;

        // Do your work...
    }
    catch(ThreadAbortException)
    {
        // Do your clean up here.
    }
}
 
Share this answer
 
v2
Comments
Alimjan Yasin 24-Aug-11 0:58am    
thanks !
Simon Bang Terkildsen 24-Aug-11 0:59am    
anytime my friend
Sergey Alexandrovich Kryukov 24-Aug-11 1:15am    
Good idea. However, once you use Abort (which is a good thing is used properly, not something unsafe as many say; it is based on the wonderful technique of exception seeding); you should also handle ThreadAbortException; I voted 4.
--SA
Simon Bang Terkildsen 24-Aug-11 1:52am    
Very true, thank you for pointing that out, I've updated the answer.
Liran Friedman 27-Apr-17 6:48am    
You have a problem with your solution.
Even after aborting the thread, the backgroundWorker.IsBusy still returns true...

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900