Reputation: 1073
I am trying to hash out the functionality of a cancel button for a WPF App. Currently there are 2 functions I am focusing on:
private void AnalysisClick(object sender, RoutedEventArgs e)
{
model.RunAnalysis();
}
private void CancelClick(object sender, RoutedEventArgs e)
{
model.RunAnalysis().Abort; //Pseudo-code, needs help!
MessageBox.Show("The Analysis was cancelled.", "Operation Cancelled", MessageBoxButton.YesNo);
}
The ' AnalysisClick ' function is started with a button called Begin. The goal of the ' CancelClick ' button is to stop the Analysis and to provide a dialog box informing the user that the test was stopped. What is the best way to achieve this?
EDIT
I am currently looking into BackgroundWorker
and Microsoft Asynchronous Programming Model per Users' suggestions.
Upvotes: 4
Views: 1961
Reputation: 6316
I agree with the comments above to your question, but if you want to try something quickly Tasks are a great way to do async operation with ability to cancel those tasks. Something like this should work or at least get you started:
private CancellationTokenSource _cancelAnalysisTask = new CancellationTokenSource();
private Task _analysisTask;
private void AnalysisClick(object sender, RoutedEventArgs e)
{
_analysisTask = Task.Factory.StartNew(() =>
{
if (_cancelAnalysisTask.IsCancellationRequested)
return;
model.RunAnalysis();
});
}
private void CancelClick(object sender, RoutedEventArgs e)
{
if (_analysisTask != null)
{
_cancelAnalysisTask.Cancel();
_analysisTask = null;
MessageBox.Show("The Analysis was cancelled.", "Operation Cancelled", MessageBoxButton.OK);
}
}
This is a quick write-up, what I would recommend is putting async functionality into your ViewModel and expose Commands. UI shouldn't really know the details of operations. Then Cancelling the Task can be written near/before the meat of the operation within the ViewModel, where it makes more sense to abort the expensive operation/loop/etc.
Upvotes: 2