Reputation: 1290
I have a button labeled "Check" that performs a long running check within a backgrounder worker block:
worker.DoWork += delegate(object s, DoWorkEventArgs args)
{
runCheck();
};
Right now while the check is running I disable the button with:
CheckButton.IsEnabled = false;
But what I would like to do is turn the "Check" button into a "Cancel" button for the .DoWork task it is currently executing so the user can cancel if wanted. Then once cancelled, the button would revert to its original "Check" form. Is this possible?
Upvotes: 0
Views: 877
Reputation: 1
I am just concerned that you will run into a cross threading scenario take a closer look at some of the Methods & Events the BackgroundWorker class offers I have used the ReportProgress method successfully in the past
Upvotes: 0
Reputation: 4480
I get the impression you have two questions: How do you change the button to be a cancel button and how do you use that button to actually cancel the task. Changing the button to say 'Cancel' is very easy, and can be done with
CheckButton.Content = "Cancel";
If you want to change the Content
of the button from a separate thread (like a background worker) then you need to use its dispatcher to handle this
CheckButton.Dispatcher.BeginInvoke(() => {CheckButton.Content = "Cancel";});
As for actually canceling the long running task, you'd need to set up a specific mechanism in the task itself that gives you a way to explicitly stop it. You could set it up on a thread on abort the thread manually, but this is a bad bad BAD idea. If it's a repeating activity, like a loop, or a long operation, you can have it check a bool
public bool CancelTask = false;
In your click event you can do:
if (CheckButton.Content.ToString() == "Check")
{
worker.DoWork += delegate(object s, DoWorkEventArgs args)
{
runCheck();
};
CheckButton.Content = "Cancel";
}
else
{
CancelTask = true;
//Some code to wait for the task to finish canceling, then set CancelTask back to false
CheckButton.Content = "Check";
}
Then inside of your task you'd need something like
if (CancelTask) return; //Or something to stop the task early
Upvotes: 1