Cancel button functionality in C # and XAML

I am trying to disable the cancel button functionality for a WPF application. I am currently focusing on two functions:

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 launched using the Begin button. The purpose of the Cancel button is to stop the analysis and provide a dialog box informing the user that the test has been stopped. What is the best way to achieve this?

EDIT I am currently studying BackgroundWorker and Microsoft 's Asynchronous Programming Model based on user suggestions.

+4
source share
1 answer

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.

+2
source

Source: https://habr.com/ru/post/1438949/


All Articles