0

So i have 2 backgroundworkers in my Winform app, just call them b1 and b2. Here is my code:

private void b1_DoWork(object sender, DoWorkEventArgs e)
{
    b2.RunWorkerAsync();
    Thread.Sleep(3000);
    b2.CancelAsync();
}



private void b2_DoWork(object sender, DoWorkEventArgs e) 
{
    Global.GetPdfThumbnail(Global.inPDF, Global.outImage);
}

What i really want is run b2 thread and make b1 thread sleep for 3 seconds and then stop b2 thread.

The problem is after b2.CancelAsync(); instruction, b2 isBusy is still true.

Please help!

sorry about my english!

tuankhoa1996
  • 131
  • 4
  • 18
  • It is all asynchronous so it takes a while for the system to stop the thread. That explains why IsBusy is true immediately after CancelAsync. You could wait for IsBusy to become true but it isn't clear what you are trying to achieve. It seems pointless to start a task, let it run for 3 seconds and than discard what has been done. Please elaborate on your primairy goal. – Martin Maat Dec 25 '15 at 20:18

1 Answers1

0

Put that to end of your b2 DoWork event:

while (b2.IsBusy)
{
    if (b2.CancellationPending)
    {
        e.Cancel = true;
        break;
    }
}
Orkun Bekar
  • 1,447
  • 1
  • 15
  • 36
  • maybe i don't understand this but i tried and this loop run forever because b1.IsBusy always true! :( – tuankhoa1996 Dec 25 '15 at 11:51
  • Not working. Program cannot reach this loop because it was stucked at GetPdfThumbnail command. this instruction take much time to process so i have to stop it :( – tuankhoa1996 Dec 25 '15 at 14:59
  • Look at [that example](http://stackoverflow.com/questions/800767/how-to-kill-background-worker-completely) then try calling abort and dispose methods instead of CancelAsync. – Orkun Bekar Dec 25 '15 at 15:19