Click here to Skip to main content
15,893,161 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i connect to my database in dowork method's of backgroundworker.
it's take a few minutes .
i want by pressing cancel button,this process stoped running.
How do this?
Posted

1 solution

You have to implement most of the cancellation code yourself, but there are a few things you have to enable on the backgroundworker itself.
The WorkerSupportsCancellation property must be set.
Then when you want to cancel, you call CancelAsync, doing this sets the cancellationpending property of the backgroundworker to true.
You have to check this property at regular intervals to check if the user requested the cancel, if you don't do this, well, it will keep on running.

C#
private void workerDoWork(object sender, DoWorkEventArgs e)
{
  for(int i = 0;i<1000000;i++){
    TimeConsumingMethod();
    if (myworker.CancellationPending){
      e.Cancel = true;
      return;
    }
  }
}

private void btnCancel_Click(object sender,RoutedEventArgs e)
{
  myWorker.CancelAsync();
}
 
Share this answer
 
v3
Comments
Hekmat90 4-Aug-12 5:44am    
my consuming method is connection.open()
and running more than once make error.
how to solve it?
Philip Stuyck 4-Aug-12 7:14am    
You cannot do that via a backgroundworker.
The cancellation process for the backgroundworker is typically for some kind of iteration process where you can cancel the iteration from continuing. Normally establishing a connection to a database should only take a few seconds.

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