Threading / Background tasks in C# using BackgroundWorker
A simple way to use thread some slower tasks, with a callback method.
It uses the BackgroundWorker. I found this to be the simplest way to achieve what I needed. The 2 tasks I used it for were image resize & sending E-mails – doing things over the web can be slow.
// Define a new BackgroundWorker BackgroundWorker bw = new BackgroundWorker(); // This will be threaded bw.DoWork += delegate(object sender, DoWorkEventArgs e) { BackgroundWorkerConfig cfg = (BackgroundWorkerConfig) e.Argument; e.Result = cfg.myVariable.ToUpper(); }; // When the thread is complete, this runs bw.RunWorkerCompleted += delegate(object sender, RunWorkerCompletedEventArgs e) { BackgroundWorkerConfig cfg = (BackgroundWorkerConfig) e.Result; Console.WriteLine("Completed: " + cfg.myVariable); }; // Start the process bw.RunWorkerAsync(new BackgroundWorkerConfig("my string goes here")); // A class used for sending configuration variables into the Worker class BackgroundWorkerConfig { public string myVariable; public BackgroundWorkerConfig(string myVariable) { this.myVariable = myVariable; } }
If you don’t need to send variables in, or care about getting them out, you can remove everything related to the BackgroundWorkerConfig – ie Batch Resizing images from a pre-defined folder.
[…] Threading / Background tasks […]