Logo

dev-resources.site

for different kinds of informations.

Tasks, BackgroundWorkers, and Threads

Published at
1/24/2023
Categories
dotnet
dotnetcore
csharp
threading
Author
devleader
Author
9 person written this
devleader
open
Tasks, BackgroundWorkers, and Threads

(This article first appeared on my blog)

Even if you’re new to C#, you’ve probably come across at least one of Tasks, Threads, or BackgroundWorkers. With a bit of additional time, it’s likely you’ve seen all three in your journey. They’re all ways to run concurrent code in C# and each has its own set of pros and cons. In this article, we will explore how each one operates at a high level. It’s worth noting that in most modern .NET applications and libraries you’ll see things converging to Tasks.

The Approach

I’ve gone ahead and created a test application that you can find here. Because this is in source control, it’s possible/likely that it will diverge from what we see in this article, so I just wanted to offer that as a disclaimer for you as the reader.

The application allows us to select different examples to run. I’ll start by pasting that code below so you can see how things work.

using System.Globalization;

internal sealed class Program
{
    private static readonly IReadOnlyDictionary<int, IExample> _examples =
        new Dictionary<int, IExample>()
        {
            [1] = new NonBackgroundThreadExample(),
            [2] = new BackgroundThreadExample(),
            [3] = new BackgroundWorkerExample(),
            [4] = new SimultaneousExample(),
        };
    private static void Main(string[] args)
    {
        Console.WriteLine("Enter the number for one of the following examples to run:");
        foreach (var entry in _examples)
        {
            Console.WriteLine("----");
            var restoreColor = Console.ForegroundColor;
            Console.ForegroundColor = ConsoleColor.Cyan;
            Console.WriteLine($"Choice: {entry.Key}");
            Console.ForegroundColor = ConsoleColor.Magenta;
            Console.WriteLine($"Name: {entry.Value.Name}");
            Console.ForegroundColor = ConsoleColor.Yellow;
            Console.WriteLine($"Description: {entry.Value.Description}");
            Console.ForegroundColor = restoreColor;
        }
        Console.WriteLine("----");
        IExample example;
        while (true)
        {
            var input = Console.ReadLine();
            if (string.IsNullOrWhiteSpace(input))
            {
                Console.WriteLine("Would you like to exit? Y/N");
                input = Console.ReadLine();
                if ("y".Equals(input, StringComparison.OrdinalIgnoreCase))
                {
                    return;
                }
                Console.WriteLine("Please make another selection.");
                continue;
            }
            if (!int.TryParse(input, NumberStyles.Integer, CultureInfo.InvariantCulture, out var exampleId) ||
                !_examples.TryGetValue(exampleId, out example))
            {
                Console.WriteLine("Invalid input. Please make another selection.");
                continue;
            }
            break;
        }
        Console.WriteLine($"Starting example '{example.Name}'...");
        Console.WriteLine("-- Before entering example method");
        example.ExecuteExample();
        Console.WriteLine("-- After leaving example method");
    }
}
Enter fullscreen mode Exit fullscreen mode

Threads

Threads are the most basic form of concurrent execution in C#. They are created and managed by the operating system, and can be used to run code in parallel with the main thread of execution. The concept of a thread is one of the most basic building blocks when we talk about concurrency in general for programming. However, it’s also a name of a class that we can directly use in C# for running concurrent code.

Threads allow you to pass in a method to execute. They also can be marked as background or not, where a background thread will be killed off when the application attempts to exit. Conversely, a non-background thread will try to keep the application alive until the thread exits.

Here is an example of creating and starting a new thread:

Thread newThread = new Thread(new ThreadStart(MyMethod));
newThread.Start();
Enter fullscreen mode Exit fullscreen mode

One major advantage of using Threads is that they have a low overhead, as they are managed directly by the operating system. However, they can be more difficult to work with than other concurrent options, as they do not have built-in support for cancellation, progress reporting, or exception handling. In C#, we’ve had access to the Thread object for a long time so it makes sense that other constructs have been built on top of this for us adding additional quality of life enhancements.

Let’s check out the first Thread example:

    public void ExecuteExample()
    {
        void DoWork(string label)
        {
            while (true)
            {
                Task.Delay(1000).Wait();
                Console.WriteLine($"Waiting in '{label}'...");
            }
        };

        var thread = new Thread(new ThreadStart(() => DoWork("thread")));
        thread.Start();

        Console.WriteLine("Press enter to exit!");
        Console.ReadLine();
    }
Enter fullscreen mode Exit fullscreen mode

In the context of our sample application, we would be able to see the method printing to the console while the Thread is running. However, when the user presses enter, the example method would exit and then the program would also try to exit. Because this Thread is not marked as background, it will actually prevent the application from terminating naturally! Try it out and see.

We can directly compare this with the second example, which has one difference: The Thread is marked as background. When you try this example out, you’ll notice that the running thread does not prevent the application from exiting!

Background Workers

BackgroundWorker is a higher-level concurrent execution option in C#. It is a component included in the System.ComponentModel namespace, and generally you see this used in GUI applications. For example, classic WinForms applications would take advantage of these.

Let’s look at our example for BackgroundWorker:

    public void ExecuteExample()
    {
        void DoWork(string label)
        {
            while (true)
            {
                Task.Delay(1000).Wait();
                Console.WriteLine($"Waiting in '{label}'...");
            }
        };

        var backgroundWorker = new BackgroundWorker();
        // NOTE: RunWorkerCompleted may not have a chance to run before the application exits
        backgroundWorker.RunWorkerCompleted += (s, e) => Console.WriteLine("Background worker finished.");
        backgroundWorker.DoWork += (s, e) => DoWork("background worker");
        backgroundWorker.RunWorkerAsync();

        Console.WriteLine("Press enter to exit!");
        Console.ReadLine();
    }
Enter fullscreen mode Exit fullscreen mode

One major advantage of using a BackgroundWorker is that it has built-in support for cancellation, progress reporting, and exception handling. It is setup slightly different in that event handlers are registered onto the BackgroundWorker. You can additionally have a completion handler and others registered to the object. Like a Thread marked as background, the BackgroundWorker will not block the application from exiting.

Tasks

Want to see how Tasks factor in? Be sure to check out my blg post that details Tasks in the same way. It summarizes with a conclusion about how you may want to use each in your programs!

threading Article's
30 articles in total
Favicon
ConcorrĂȘncia e paralelismo em Python
Favicon
Navigating Concurrency for Large-Scale Systems
Favicon
Common Java Developer Interview Questions and Answers on multithreading, garbage collection, thread pools, and synchronization
Favicon
Real-time plotting with pyplot
Favicon
A Quick Guide to the Python threading Module with Examples
Favicon
Understanding Threading and Multiprocessing in Python: A Comprehensive Guide
Favicon
I Asked Copilot to Explain Threading in Python to a Dog
Favicon
Introduction to GCD (Grand Central Dispatch)
Favicon
Achieving multi-threading by creating threads manually in Swift
Favicon
Swift Concurrency
Favicon
Python Multithreading: Unlocking Concurrency for Better Performance
Favicon
Choosing the best asynchronous library in Python
Favicon
Two Lines of Code Eluded me for Several Months
Favicon
A Comprehensive Guide to Python Threading: Advanced Concepts and Best Practices
Favicon
Thread synchronisation
Favicon
Rust Learning Note: Multithreading
Favicon
Async vs Threading vs Multiprocessing in Python
Favicon
02.Android Background Task
Favicon
How to handle threads with multiple gunicorn workers to get consistent result
Favicon
Tasks, BackgroundWorkers, and Threads
Favicon
Understanding Task.WhenAll in C#
Favicon
Producer/consumer pipelines with System.Threading.Channels
Favicon
How to auto-refresh Realm inside Android WorkManager
Favicon
Understanding Task in .Net
Favicon
Como resolvemos um bug que afetava 3000 usuårios e nos custaria milhÔes por ano
Favicon
Java Thread Programming (Part 1)
Favicon
So, you want to launch several threads in Python and something does not work?
Favicon
Higher level threading in C++
Favicon
Solve the scenario - using Thread synchronization in Dotnet - CountDownEvent
Favicon
Đ§Ń‚ĐŸ ĐČ ĐżŃ€ĐŸŃ†Đ”ŃŃĐ” тДбД ĐŒĐŸĐ”ĐŒ?

Featured ones: