Quick comparison of concurrent code execution techniques in .NET desktop applications

In .NET desktop applications there are many ways to execute code concurrently (or in parallel) on a different thread. And there are times when a skilled C# .NET developer needs to write code that will execute in parallel for some reason. In this post I have tried to compile possible ways that I could find to achieve concurrent code execution in .NET desktop applications.

This should help you to choose the right way of concurrent (or parallel) code execution in your code.

Quick comparison of classes that facilitates concurrent code execution in .NET desktop applications

Sr. No. Class name (including namespace) WinForm UI Sync options WPF UI Sync options Unhandled Exception Behavior Operation Cancellation option
1 System.Threading.Thread Using Control.Invoke method Dispatcher.Invoke Application crash Explicit code needs to be written
2 System.Threading.ThreadPool Using Control.Invoke method Dispatcher.Invoke Application crash Explicit code needs to be written
3 System.ComponentModel.BackgroundWorker ProgressChanged and RunWorkerCompleted events. ProgressChanged and RunWorkerCompleted events. Any exceptions raised in DoWork event handler can be obtained in RunWorkerCompleted event. Using CancelAsync method and implementation around checking cancellation request.
4 System.Threading.Tasks.Task TaskScheduler.FromCurrentSynchronizationContext() TaskScheduler.FromCurrentSynchronizationContext() Exceptions are reported only when tasks are awaited or result is obtained from task. Using CancellationToken. Task exeuction code needs to use CancellationToken to cancel running operation and implementation around checking cancellation request.
5 System.Threading.Timer Using Control.Invoke method
Or using Control.BeginInvoke method
Using Dispatcher.Invoke method
Or using Dispatcher.BeginInvoke method
Application crash Explicit code needs to be written
6 System.Timers.Timer Using Timer.SynchronizingObject Possible by implementing ISynchronizeInvoke interface. No crash observed. Explicit code needs to be written
7 System.Windows.Forms.Timer N/A
Single threaded; runs on UI thread only.
N/A Application crash N/A
8 System.Windows.Threading.DispatcherTimer N/A N/A
Single threaded; runs on UI thread only.
Application crash N/A

 

Concurrent code execution techniques in .NET desktop applications