Tag Archive: c#

Writing thread-safe event handlers with the Task Parallel Library in .NET 4.0

Microsoft .NET

Download Example Code
TasksWithThreadSafeEvents.zip

In this article we will be using the following technologies:

  • .NET 4.0
  • Windows Forms (WinForms)
  • Task Parallel Library (TPL, part of .NET 4.0)

In a nutshell, I am talking about writing thread-safe events for WinForms. I’ve not ventured into the world of WPF quite yet, so this article may or may not apply to WPF.

Now, with that said, you may be familiar with the concept of BeginInvoke, EndInvoke, and Invoke to access WinForms controls safely from other threads. The amount of code to do that can be quite cumbersome, and to me it looks like speghetti. Another way to do it was by using ISynchronizeInvoke which you could wrap into a helper class, and do invoking in a single line of code. These methods all work great.

There are quite a few articles that explain how to do thread-safe and synchronized events with the Task Parallel Library, but they often are long and complicated. The other problem with the majority of these articles out there all assume one, single, horrific thing: You will always be writing your parallel code inside the form and have access to your controls other other referencable objects. Furthermore, they all seem to implement some sort of helper class that comes as an extra. In this article, my aim is a bit more specific. Take the System.Net.WebClient class for example. It exposes an event called DownloadProgressChanged. You know what is great about this? It’s thread-safe, and it doesn’t have a clue about your form or controls. That’s what this article is about. I am going to show you how to write a class with completely thread-safe events using the TPL and just a few lines of code.

The code:

//-----------------------------------------------------------------------------
// <copyright file="Counter.cs" company="DCOM Productions">
//     Copyright (c) DCOM Productions.  All rights reserved.
// </copyright>
//-----------------------------------------------------------------------------

namespace TasksWithThreadSafeEvents.Objects {
    using System;
    using System.Threading.Tasks;
    using System.Threading;

    internal class Counter {
        // CLR generated constructor

        #region Events

        /// <summary>
        /// Occurs when the counter has counted
        /// </summary>
        public event EventHandler CountChanged;
        private void OnCountChanged() {
            if (CountChanged != null) {
                CountChanged(this, new EventArgs());
            }
        }

        /// <summary>
        /// Occurs when the counter has completed counting
        /// </summary>
        public event EventHandler CountCompleted;
        private void OnCountCompleted(Task task) {
            if (CountCompleted != null) {
                CountCompleted(this, new EventArgs());
            }
        }

        #endregion

        #region Properties

        private int m_Maximum = 100;
        /// <summary>
        /// Sets the maximum value the counter will count to 
        /// </summary>
        public int Maximum {
            get {
                return m_Maximum;
            }
            set {
                m_Maximum = value;
            }
        }

        #endregion

        #region Methods

        private void Count() {
            for (int i = 0; i < Maximum; i++) {
                Thread.Sleep(50);
            }
        }

        /// <summary>
        /// Runs the counter by starting from 0 and incrementing by one, until the counter reaches its maximum
        /// </summary>
        public void Run() {
            Task.Factory.StartNew(Count).ContinueWith(OnCountCompleted);
        }

        #endregion
    }
}

I shouldn’t have to explain the code, but I will say that the main difference you will see in this event model is that OnCountCompleted defines an argument of type Task. This is because we must specify a Action<Task> when calling ContinueWith when we run our task. We don’t care about the Task object in the event handler, we just want to notify the event that it was completed, and with this approach having to pass an Action<Task> is just a small side-effect.

Often in development you want to write components like this (not specifically a counter), but essentially a class (or wrapper) that does all the work you need to, and is thread-safe at the same time. The reason we do this is we don’t want to have to make it thread-safe everywhere we use it in UI. If I have a class that does not provide thread-safe events, that means I have to write all this thread-safe code in each UI that I use it in. The class we just went over is extremely simple, so let’s wire-up the progress.

First, we need to add a TaskScheduler field to the class.

#region Fields

private TaskScheduler m_TaskScheduler = TaskScheduler.FromCurrentSynchronizationContext();

#endregion

This should be pretty self-explanatory, but in a nutshell we define this at class-scope, and it creates the object on the same thread that the class is created on (of course). So essentially, when you create the Counter class somewhere in your WinForm, the TaskScheduler is created on the same thread as the form: your UI thread.

Next, we need to actually report progress in our Count() method that actually does the counting. The cool thing about the Task Parallel Library is we can do this in a single line of code.

private void Count() {
    for (int i = 0; i &lt; Maximum; i++) {         
        Thread.Sleep(50);         
            Task.Factory.StartNew(() =&gt; OnCountChanged(),
            CancellationToken.None,
            TaskCreationOptions.None,
            m_TaskScheduler)
        .Wait();
    }
}

We are simply starting a new task using the existing TaskFactory, and hooking it up to our method that invokes the event handler. We don’t need to specifiy anything special for arguments, but we need to make sure we pass in our TaskScheduler. This is important, because the task scheduler will invoke the task on the thread the task scheduler is on: the UI thread.

The second important thing is that we are calling the Wait method. The reason we are doing this is because we want to give whatever hooks up to the event time to execute their logic. For example, a progress bar to update and paint.

That’s all there is too it.. let’s use the code in a simple WinForms app with a progress bar and a button.

//-----------------------------------------------------------------------------
// <copyright file="ShellForm.cs" company="DCOM Productions">
//     Copyright (c) DCOM Productions.  All rights reserved.
// </copyright>
//-----------------------------------------------------------------------------

namespace TasksWithThreadSafeEvents.Forms {
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    using TasksWithThreadSafeEvents.Objects;

    public partial class ShellForm : Form {
        /// <summary>
        /// Instantiates a new instance of the TasksWithThreadSafeEvents.Forms.ShellForm class
        /// </summary>
        public ShellForm() {
            InitializeComponent();
        }

        private void OnButtonClick(object sender, EventArgs e) {
            Counter counter = new Counter();
            counter.CountChanged += OnCountChanged;
            counter.CountCompleted += OnCountCompleted;
            counter.Maximum = uxProgressBar.Maximum;
            uxProgressBar.Value = 0;
            counter.Run();
        }

        private void OnCountChanged(object sender, EventArgs e) {
            uxProgressBar.Value++;
        }

        private void OnCountCompleted(object sender, EventArgs e) {
            MessageBox.Show("The counter has reached its maximum", "Counter", 
                MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
    }
}

The code looks clean, and it was very little work to implement. You could of course modify the code to actually report a value for progress if you wanted by creating your own class deriving from EventArgs, and passing the for-loop indexer to the event args of the event. I hope this helps those out there looking to write simple, thread-safe classes using the Task Parallel Library.

Download Example Code
TasksWithThreadSafeEvents.zip

The myth of misusage of the var keyword since C# 3.0

Microsoft .NET

C# 3.0 introduced a new keyword, var. The var keyword allows you to utilize type inference at compile time which is a really cool feature. Here’s an extremely basic example.

var message = "Hello World";

This should be self-explanatory: The compiler will resolve the local variable ‘message’ to be of type ‘string’, which is inferred by the value in the assignment statement. This is pretty cool, but it was never meant to change the C# specification or rid of using strongly typed names. The optimal usage of the var keyword is when you are dealing with Anonymous Types, and Generics. It was actually introduced along with the release of Linq in C# 3.0 which deals with these two language features quite often.

There are other scenarios where var is useful though, take this statement:

List<KeyValuePair<AccountRoles[], ToolStripMenuItem>> m_GuardedMenuItems = new List<KeyValuePair<AccountRoles[], ToolStripMenuItem>>();

That is a pretty knarly declaration and assignment statement, and this is a scenario where the var keyword would actually be recommended to improve readability to:

var m_GuardedMenuItems = new List<KeyValuePair<AccountRoles[], ToolStripMenuItem>>();

This also benefits the language outside the scope of the compiler. You can easily see that the first sample causes the syntax highlighter on this page to have to scroll – so for programming books, reference material, and blogs like this var has its use outside the realm of actual C# programs.

Bad: When the type is not obvious.

var doc = Factory.GetDocument(); // What is doc?

Good: When the type is obvious.

var text = new StringBuilder(); // We easily can see it is inferred to StringBuilder

The truth is, you can come up with more good examples of when to use var, then when not to use it. Another example would be refactoring. Say you have the following.

List<Order> orders = Factory.GetOrders();

Later down the road if the return type of Factory.GetOrders() were to change, you would have to go refactor every declaration that uses that method. However with var, you would not have had to done this if you used var in the first place.

var is pretty controversial, but the general consensus from the experts is its not as bad as everyone thinks.

Dangers of the public access modifier.

Microsoft .NET

Did you know that the public access modifer in C# is essentially the equivalent to extern in C++? According to the C# 4.0 language specification, it is.

People need to be careful with the public keyword. public in C# is not equivalent to public in C++! In C++, it means “internal to my compilation unit.” In C#, it means what extern meant in C++ (i.e., everybody can call it). This is a huge difference!

This was best said by Krzysztof Cwalina, quoted in the revised Fourth Edition of The C# Programming Language. It actually makes more sense to me know when I browse the .NET Framework source code as to why I see Microsoft using internal access modifiers quite a bit more often. If you are rusty and don’t quite remember the access modifiers they are:

public
Access not limited.

protected
Access limited to this class or classes derived from this class.

internal
Access limited to this program.

protected internal
Access limited to this program or classes derived from this class.

private
Access limited to this class.

But remember, as Christian Nagel said it best, that internal is rather best described as being “access limited to this assembly”, because a program can be defined as a collection of executables and assemblies, and a class marked as internal cannot be accessed by an assembly referencing it.

Why abstraction can be detrimental.

Microsoft .NET

The other day someone asked a question about the relation between the Socket class, and the UdpClient class. Specifically, what is the relation? While the answer is simple because UdpClient is merely wrapper around a UDP initialized socket, this also lead me to thinking more about abstraction.

So what is abstraction?
Take the following code sample.

XDocument xdoc = XDocument.Load(ConfigurationFilePath);
string boolstr = xdoc
    .Element("ApplicationConfiguration")
        .Element("Settings")
            .Element("AutoLogin")
            .Attribute("Enabled")
            .Value;
return boolstr.Equals(Boolean.TrueString, StringComparison.OrdinalIgnoreCase);

Imagine if you had to write that every time you wanted to retrieve a value in a configurationfile. That’s a lot of replicated code. In it’s simplist form, a C# Property is a form of abstraction – it hides the underlying implementation. Functions can also be considered abstraction. So, in essence we could do the following.

/// <summary>
/// Gets or sets a System.Boolean value indicating whether automatic login is enabled
/// </summary>
public static bool AutoLoginEnabled {
    get {
        XDocument xdoc = XDocument.Load(ConfigurationFilePath);
        string boolstr = xdoc
            .Element("ApplicationConfiguration")
                .Element("Settings")
                    .Element("AutoLogin")
                    .Attribute("Enabled")
                    .Value;
        return boolstr.Equals(Boolean.TrueString, StringComparison.OrdinalIgnoreCase);
    }
    set {
        XDocument xdoc = XDocument.Load(ConfigurationFilePath);
        xdoc.Element("ApplicationConfiguration")
                .Element("Settings")
                    .Element("AutoLogin")
                    .Attribute("Enabled")
                    .Value = value ? Boolean.TrueString : Boolean.FalseString;
        xdoc.Save(ConfigurationFilePath);
    }
}

So what happened here? We took a segment of code and wrapped in a C# Property, hiding the underlying implementation. This is called abstraction. So now we can easily just call SomeClass.AutoLoginEnabled = true, and the Property takes care of the dirty work underneath. Now this is obviously a very basic concept of abstraction. Generally, real-world abstraction in program code means asbtracting base classes, services, and other really complex things, but the idea here to understand the basic concept of abstraction.

How this relates to UdpClient and Socket
I always thought the Socket class was easy enough, but I often find that quite a few people prefer to use UdpClient or TcpClient, because they feel that it is easier to work with. This may be the case, but even the Socket class is a layer of abstraction as it is a wrapper around the Berkeley socket interface.

C# makes abstraction easy to do. It’s plain and simple. The reason this is dangerous though, is because often times developers create so many layers of abstraction, that it is often hard for either Jr. Developers or new people to the code to learn what is going on. I often find that many beginners in programming can understand the fundamentals of the code they are using. So in this case a beginner programmer may learn the UdpClient class inside-and-out, but in the end, they may not have a single clue about how that class is actually implemented, what goes on underneath, and how network programming is actually done.

In short, absraction is a good thing – when you also take the time to learn and understand the underlying implementations. However, you can definitely see how this can act negatively on a developer’s understanding of program code.