I agree with the above comments on your question, but if you want to try something fast quickly Tasks are a great way to do asynchronous work with the ability to cancel these tasks. Something like this should work, or at least get 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 report, I would recommend adding aync functions to your ViewModel and issuing commands. The user interface does not need to know the details of operations. Then a task cancellation can be written near / before the operation meat in the ViewModel, where it makes sense to interrupt the expensive operation / cycle / etc.
source share