AOP

Executing on the Background Thread with PostSharp

Background ThreadIn my last two PostSharp blog posts, I looked at creating some custom attributes that you could use to get custom behavior out of PostSharp. Of course, I was implementing simple functionality and in fact, PostSharp had most of if not all of those features already built in.

Today, I want to dig in a little more to some of the built in power of PostSharp. To do this, I had to sign up for the 45 day evaluation license for PostSharp Ultimate. I had been putting that off to do as much “free stuff” as I could, but I really wanted to see what PostSharp could do, so I fired up the evaluation.

I created a very simple UI that looks like this:
Simple "Long Running Process" UI

When you click the buttons, I call a class that just sleeps for three seconds and returns to simulate some slow process.

public void LongRunningOperationBlocking()
{
    Thread.Sleep(3000);
    return;
}

I created code that will run this blocking process and then when the UI thread is free again, it displays a message box with whatever was in the textbox. Here is the UI in action. Note that I cannot select the text after clicking the button because the UI is locked up for 3 seconds.
Blocking Fail

However, with PostSharp, we can easily execute these long running methods on a background thread. As long as the method returns void, the context menu will reveal the “Execute method in the background” option like this:
The PostSharp Context Menu Showing Background Thread Option

After selecting that option, you get this wizard:
The PostSharp Add a Feature Wizard

The sum total of the “visible” changes is that our other method got a new attribute, “[Background]”

[Background]
public void LongRunningOperationBackground()
{
    Thread.Sleep(3000);
    return;
}

But, the win is that now when I click the button, the UI returns immediately and we see the message box right away, even while the long running process is going.
Blocking Fail

That is a gigantic amount of threading code that we don’t have to write. It is only probably 4-6 lines per method, but you have to write the same thing over and over again for every method you want to have do work on a background thread. Of course, any time you can just cut out “boilerplate code”, you make your code not only easier to write, but easier to read and discern intent. And that is “A Good Thing™”!

As always, you can download the code for this series from my Github repository for it. The path to this post’s code is here.