Multithreading WinForm. Use backgroundWorker or not?

I have a simple application that runs a number of data intensive tasks. I am not very experienced with WinForms, and I was wondering how to do this without locking the interface. Is it possible to reuse backgroundWorker or is there another way to do this?

thanks

+6
source share
4 answers

backgroundWorker .

its advantage is that it allows you to update the progress bar and interact with user interface controls. ( WorkerReportsProgress )

It also has a cancellation mechanism. ( WorkerSupportsCancellation )

enter image description here

+6
source

BackgroundWorker is a stream that also includes notification synchronization. For example, if you want to update your user interface when scanning is completed, regular Thread will not be able to access user interface objects (only a user interface thread can do this); therefore, BackgroundWorker provides a Completed event handler that runs in the user interface thread when the operation completes.

for more information see: Walkthrough: Multithreading with BackgroundWorker (MSDN)

and a simple code example:

 var worker = new System.ComponentModel.BackgroundWorker(); worker.DoWork += (sender,e) => Thread.Sleep(60000); worker.RunWorkerCompleted += (sender,e) => MessageBox.Show("Hello there!"); worker.RunWorkerAsync(); 
+3
source

A background worker would be a good choice to start with

For more information, see here http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx

+2
source

You can use BackgroundWorker for such requirements. Below is a sample that updates a label status based on percentage task [long running] completion . In addition, there is an example business class that sets some value, and the value is returned to the user interface through the ProgressChanged handler. DoWork is the place where you write your long task. Copy. Paste the code below by adding a shortcut and backgroundworker to the Winforms application and take a picture. You can debug various handlers [RunWorkerCompleted, ProgressChanged, DoWork] and look at the InitWorker method. Also pay attention to the cancellation feature .

 using System.ComponentModel; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form3 : Form { private BackgroundWorker _worker; BusinessClass _biz = new BusinessClass(); public Form3() { InitializeComponent(); InitWorker(); } private void InitWorker() { if (_worker != null) { _worker.Dispose(); } _worker = new BackgroundWorker { WorkerReportsProgress = true, WorkerSupportsCancellation = true }; _worker.DoWork += DoWork; _worker.RunWorkerCompleted += RunWorkerCompleted; _worker.ProgressChanged += ProgressChanged; _worker.RunWorkerAsync(); } void DoWork(object sender, DoWorkEventArgs e) { int highestPercentageReached = 0; if (_worker.CancellationPending) { e.Cancel = true; } else { double i = 0.0d; int junk = 0; for (i = 0; i <= 199990000; i++) { int result = _biz.MyFunction(junk); junk++; // Report progress as a percentage of the total task. var percentComplete = (int)(i / 199990000 * 100); if (percentComplete > highestPercentageReached) { highestPercentageReached = percentComplete; // note I can pass the business class result also and display the same in the LABEL _worker.ReportProgress(percentComplete, result); _worker.CancelAsync(); } } } } void RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { if (e.Cancelled) { // Display some message to the user that task has been // cancelled } else if (e.Error != null) { // Do something with the error } } void ProgressChanged(object sender, ProgressChangedEventArgs e) { label1.Text = string.Format("Result {0}: Percent {1}",e.UserState, e.ProgressPercentage); } } public class BusinessClass { public int MyFunction(int input) { return input+10; } } } 
+2
source

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


All Articles