public BackgroundWorkerView() { InitializeComponent(); DataContext = this; _backgroundWorker = new BackgroundWorker(); _backgroundWorker.WorkerReportsProgress = true; _backgroundWorker.WorkerSupportsCancellation = true; _backgroundWorker.DoWork += BackgroundWorker_DoWork; _backgroundWorker.RunWorkerCompleted += BackgroundWorker_RunWorkerCompleted; _backgroundWorker.ProgressChanged += BackgroundWorker_ProgressChanged; MyTestObject = new MyObject() { MyDouble = 134.34, MyString = "Hello, world", IntList = new ObservableCollection<int>() }; }
private void MyWork(MyObject parameter) { Action<int> workMethod = i => AutoNumberTextBox.Text = i.ToString(); var n = 100; for (int i = 0; i < n; i++) { if (_backgroundWorker.CancellationPending) return; if (_backgroundWorker.WorkerReportsProgress) _backgroundWorker.ReportProgress(i * 100 / n); Thread.Sleep(TimeSpan.FromSeconds(0.05)); AutoNumberTextBox.Dispatcher.BeginInvoke(DispatcherPriority.Normal, workMethod, i); Dispatcher.BeginInvoke(DispatcherPriority.Normal, (ThreadStart) (() => { parameter.MyString = i.ToString(); parameter.IntList.Add(i); })); } }