Follow these steps to use a background worker, to perform the long running process, and to count the odd and even numbers within a range:
- From Solution Explorer, navigate to the MainWindow.xaml.cs file.
- Add the following using namespace—System.ComponentModel, so that we can use the BackgroundWorker class.
- Inside the OnCalculateClicked event, instead of calling ThreadPool to execute the operation, create an instance of the BackgroundWorker class.
- Register the worker events DoWork and RunWorkerCompleted.
- Call the RunWorkerAsync method of the background worker by passing the numeric range as an argument. The argument accepts objects, hence, we will use Tuple<int, int> as the data type for simplicity. The complete code looks as follows:
private void OnCalculateClicked(object sender, RoutedEventArgs e) { totalOdd = 0; totalEven = 0; if (int.TryParse(fromValue.Text, out int from) && int.TryParse(toValue.Text, out int to)...