Automatically inject fakes in test fixture with FakeItEasy

Very poorPoorAverageGoodExcellent (2 votes) 
Loading...Loading...

Today I’d like to share a nice feature I discovered recently in FakeItEasy.

When you write unit tests for a class that takes dependencies, you typically need to create fake/mock dependencies and manually inject them into the SUT (System Under Test), or use a DI container to register the fake dependencies and construct the SUT. This is a bit tedious, and a few months ago I came up with an auto-mocking Unity extension to make it easier. Now I just realized that FakeItEasy offers an even better solution: just declare the dependencies and SUT as fields or properties in your test fixture, and call Fake.InitializeFixture on the fixture to initialize them. Here’s how it looks:

    public class BlogManagerTests
    {
        [Fake] public IBlogPostRepository BlogPostRepository { get; set; }
        [Fake] public ISocialNetworkNotifier SocialNetworkNotifier { get; set; }
        [Fake] public ITimeService TimeService { get; set; }

        [UnderTest] public BlogManager BlogManager { get; set; }

        public BlogManagerTests()
        {
            Fake.InitializeFixture(this);
        }

        [Fact]
        public void NewPost_should_add_blog_post_to_repository()
        {
            var post = A.Dummy<BlogPost>();

            BlogManager.NewPost(post);

            A.CallTo(() => BlogPostRepository.Add(post)).MustHaveHappened();
        }

        [Fact]
        public void PublishPost_should_update_post_in_repository_and_publish_link_to_social_networks()
        {
            var publishDate = DateTimeOffset.Now;
            A.CallTo(() => TimeService.Now).Returns(publishDate);

            var post = A.Dummy<BlogPost>();

            BlogManager.PublishPost(post);

            Assert.Equal(BlogPostStatus.Published, post.Status);
            Assert.Equal(publishDate, post.PublishDate);

            A.CallTo(() => BlogPostRepository.Update(post)).MustHaveHappened();
            A.CallTo(() => SocialNetworkNotifier.PublishLink(post)).MustHaveHappened();
        }
    }

The SUT is declared as a property marked with the [UnderTest] attribute. Each dependency that you need to manipulate is declared as a property marked with the [Fake] attribute. Fake.InitializeFixture then initializes the SUT, creating fake dependencies on the fly, and assigns those dependencies to the corresponding properties.

I really like how clean the tests look with this technique; the boilerplate code is reduced to a minimum, all you have to do is configure the dependencies where necessary and get on with your tests.

Two remarks about the code above:

  • You can use private fields instead of public properties for the fakes and SUT, but since the fields are never explicitly set in code, it raises a compiler warning (CS0649), so I prefer to use properties.
  • The tests in my example use xUnit, so I put the call to Fake.InitializeFixture in the fixture constructor, but if you use another test framework like NUnit or MSTests, you would typically put it in the setup method.

Also, note that there are limits to the scenarios supported by this approach:

  • only constructor injection is supported, not property injection (i.e. the dependencies must be constructor parameters of the SUT)
  • named dependencies are not supported; only the type is taken into account, so you can’t have multiple distinct dependencies with the same type
  • dependency collections are not supported (i.e. if your class receives a collection of dependencies, e.g. IFooService[])

Using multiple cancellation sources with CreateLinkedTokenSource

Very poorPoorAverageGoodExcellent (No Ratings Yet) 
Loading...Loading...

Async programming in C# used to be hard; thanks to .NET 4’s Task Parallel Library and C# 5’s async/await feature, it has become fairly easy, and as a result, is becoming much more common. At the same time, a standardized approach to cancellation has been introduced : cancellation tokens. The basic idea is that you create a CancellationTokenSource that controls the cancellation, and pass the token it provides to the method that you want to be able to cancel. That method will then pass it to the other methods it calls, if they can be canceled, and/or regularly check if cancellation was requested. Upon cancellation, the method will typically throw an OperationCanceledException. Quick and dirty example:

private readonly IBusinessService _businessService;
private CancellationTokenSource _cancellationSource;
private Task _asyncOperation;

private void StartAsyncOperation()
{
    if (_asyncOperation != null)
        return;
    var _cancellationSource = new CancellationTokenSource();
    _asyncOperation = _businessService.DoSomethingAsync(_cancellationSource.Token);
}

// async void is bad; like I said, this is a quick and dirty example
private async void StopAsyncOperation()
{
    try
    {
        _cancellationSource.Cancel();
        // wait for the operation to finish
        await _asyncOperation;
    }
    catch (OperationCanceledException)
    {
        // Operation was successfully canceled
    }
    catch (Exception)
    {
        // Oops, something went wrong
    }
    finally
    {
        _asyncOperation = null;
        _cancellationSource.Dispose();
        _cancellationSource = null;
    }

...

class BusinessService : IBusinessService
{
    public async Task DoSomethingAsync(CancellationToken cancellationToken)
    {
        var data = await GetDataFromServerAsync(cancellationToken);
        foreach (string line in data)
        {
            cancellationToken.ThrowIfCancellationRequested();
            await ProcessLineAsync(line, cancellationToken);
        }
    }

    ...
}

In this case, StopAsyncOperation would be called, for instance, if the user chooses to abort the operation.

This all works pretty well and is rather easy to setup. But what if there is another reason to cancel the operation, known only by the BusinessService and outside the control of the calling method? That’s where the CancellationSource.CreateLinkedTokenSource method comes into play; basically, this method creates a cancellation source that will be canceled when any of the specified tokens is canceled.

Let’s start with a simple case: you have another cancellation token that you also want to take into account. The code would look like this:

    public async Task DoSomethingAsync(CancellationToken cancellationToken)
    {
        var otherToken = GetOtherCancellationToken();
        using (var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, otherToken))
        {
            var data = await GetDataFromServerAsync(linkedCts.Token);
            foreach (string line in data)
            {
                linkedCts.Token.ThrowIfCancellationRequested();
                await ProcessLineAsync(line, linkedCts.Token);
            }
        }
    }

We created a linked cancellation source based on the two cancellation tokens, then used the token from this new source instead of cancellationToken. If either cancellationToken or otherToken is canceled, linkedCts.Token will be canceled as well. If necessary, the calling code can detect how the operation was canceled by checking the CancellationToken property of the OperationCanceledException.

Now let’s see a slightly more difficult case: the second cancellation source is actually an event. You want to cancel the operation when the event occurs, in addition to user cancellation represented by the cancellationToken parameter. So you need to subscribe to the event and trigger the cancellation when it occurs. Here’s a way to do it:

    public async Task DoSomethingAsync(CancellationToken cancellationToken)
    {
        using (var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken))
        {
            EventHandler handler = (sender, e) => linkedCts.Cancel();
            try
            {
                SomeEvent += handler;
                var data = await GetDataFromServerAsync(linkedCts.Token);
                foreach (string line in data)
                {
                    linkedCts.Token.ThrowIfCancellationRequested();
                    await ProcessLineAsync(line, linkedCts.Token);
                }
            }
            finally
            {
                SomeEvent -= handler;
            }
        }
    }

Here we only pass cancellationToken to CreateLinkedTokenSource, and we directly cancel linkedCts when the event is raised. The code is getting a bit convoluted, but it achieves the desired result.

I can’t really give you a specific real-world use case of this technique, because the cases where I used it are too specific to be of public interest, but I can outline the general scenario. I have a long running operation that is made up of multiple long running operations. The whole operation can be canceled globally, and each of the sub-operations can also be canceled individually, without affecting the others. Here’s the rough outline of what it looks like:

async Task GlobalOperationAsync(CancellationToken cancellationToken)
{
    foreach (var subOperation is SubOperations)
    {
        cancellationToken.ThrowIfCancellationRequested();
        var subToken = subOperation.GetSpecificCancellationToken();
        using (var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, subToken))
        {
            try
            {
                await subOperation.RunAsync(linkedCts.Token);
            }
            catch (OperationCanceledException ex)
            {
                // Rethrow only if global cancellation was requested
                if (cancellationToken.IsCancellationRequested)
                    throw;
                    
                // otherwise continue running the other sub-operations
            }
        }
    }
}

Note that even though CancellationToken was introduced with the TPL and all the examples I gave were asynchronous, nothing prevents you from using this technique with synchronous code.

I hope you find this helpful. Have a great New Year’s Eve celebration and a happy new year!

Explicitly switch to the UI thread in an async method

Very poorPoorAverageGoodExcellent (1 votes) 
Loading...Loading...

Async code is a great way to keep your app’s UI responsive. You can start an async operation from the UI thread, await it without blocking the UI thread, and naturally resume on the UI thread when it’s done. This is a very powerful feature, and most of the time you don’t even need to think about it; it “just works”. However, this works only if the async operation is started from a thread that has a synchronization context (such as the UI thread in Windows Forms, WPF or WinRT). If you don’t have a sync context when the async operation starts, or if resuming on the sync context is explicitly disabled with ConfigureAwait(false), then the method resumes on a thread pool thread after the await, and there is no obvious way to get back to the UI thread.

For instance, let’s assume you want to do something like this:

public async void btnStart_Click(object sender, RoutedEventArgs e)
{
    lblStatus.Text = "Working...";
    
    // non blocking call
    var data = await GetDataFromRemoteServerAsync().ConfigureAwait(false);
    // blocking call, but runs on a worker thread
    DoSomeCpuBoundWorkWithTheData(data);
    
    // Oops, not on the UI thread!
    lblStatus.Text = "Done";
}

This method starts an async operation to retrieve some data, and doesn’t resume on the UI thread, because it has some work to do in the background. When it’s done, it tries to update the UI, but since it’s not on the UI thread, it fails. This is a well known issue, and there are several workarounds. The most obvious one is to explicitly marshall the action to the dispatcher thread:

Dispatcher.Invoke(new Action(() => lblStatus.Text = "Done"));

But it’s not very elegant and readable. A better way to do it is simply to extract the part of the method that does the actual work to another method:

public async void btnStart_Click(object sender, RoutedEventArgs e)
{
    lblStatus.Text = "Working...";
    await DoSomeWorkAsync();
    lblStatus.Text = "Done";
}

private async Task DoSomeWorkAsync()
{
    // non blocking call
    var data = await GetDataFromRemoteServerAsync().ConfigureAwait(false);
    // blocking call, but runs on a worker thread
    DoSomeCpuBoundWorkWithTheData(data);
}

It takes advantage of the normal behavior of await, which is to resume on the captured sync context if it was available.

However, there might be some cases where it’s not practical to split the method like this. Or perhaps you want to switch to the UI thread in a method that didn’t start on the UI thread. Of course, you can use Dispatcher.Invoke, but it doesn’t look very nice with all those lambda expressions. What would be nice would be to be able to write something like this:

await syncContext;

Well, it’s actually pretty simple to do: we just need to create a custom awaiter. The async/await feature is pattern-based; for something to be “awaitable”, it must:

  • have a GetAwaiter() method (which can be an extension method), which returns an object that:
    • implements the INotifyCompletion interface
    • has an IsCompleted boolean property
    • has a GetResult() method that synchronously returns the result (or void if there is no result)

So, we need to create an awaiter that captures a synchronization context, and causes the awaiting method to resume on this synchronization context. Here’s how it looks like:

public struct SynchronizationContextAwaiter : INotifyCompletion
{
    private static readonly SendOrPostCallback _postCallback = state => ((Action)state)();

    private readonly SynchronizationContext _context;
    public SynchronizationContextAwaiter(SynchronizationContext context)
    {
        _context = context;
    }

    public bool IsCompleted => _context == SynchronizationContext.Current;

    public void OnCompleted(Action continuation) => _context.Post(_postCallback, continuation);

    public void GetResult() { }
}
  • The constructor takes the synchronization context that the continuation needs to resume on.
  • The IsCompleted property returns true only if we’re already on this synchronization context.
  • OnCompleted is called only if IsCompleted was false. It accepts a “continuation”, i.e. that code that must be executed when the operation completes. In an async method, the continuation is just the code that is after the awaited call. Since we want that continuation to run on the UI thread, we just post it to the sync context.
  • GetResult() doesn’t need to do anything; it will just be called as part of the continuation.

Now that we have this awaiter, we just need to create a GetAwaiter extension method for the synchronization context that returns this awaiter:

public static SynchronizationContextAwaiter GetAwaiter(this SynchronizationContext context)
{
    return new SynchronizationContextAwaiter(context);
}

And we’re done!

The original method can now be rewritten like this:

public async void btnStart_Click(object sender, RoutedEventArgs e)
{
    var syncContext = SynchronizationContext.Current;
    lblStatus.Text = "Working...";
    
    // non blocking call
    var data = await GetDataFromRemoteServerAsync().ConfigureAwait(false);
    // blocking call, but runs on a worker thread
    DoSomeCpuBoundWorkWithTheData(data);
    
    // switch back to the UI thread
    await syncContext;
    lblStatus.Text = "Done";
}

[WPF] Prevent the user from pasting an image in a RichTextBox

Very poorPoorAverageGoodExcellent (No Ratings Yet) 
Loading...Loading...

WPF’s RichTextBox control is quite powerful, and very handy if you need to accept rich text input. However, one of its features can become an issue: the user can paste an image. Depending on what you intend to do with the text entered by the user, you might not want that.

When I googled for a way to prevent that, the only solutions I found suggested to intercept the Ctrl-V keystroke, and swallow the event if the clipboard contains an image. There are several issues with this approach:

  • it doesn’t prevent the user from pasting using the context menu
  • it won’t work if the command’s shortcut has been changed
  • it doesn’t prevent the user from inserting an image using drag and drop

Since I wasn’t satisfied with this solution, I used the .NET Framework Reference Source website to look for a way to intercept the paste operation itself. I followed the code from the ApplicationCommands.Paste property, and eventually found the DataObject.Pasting attached event. It’s not a place where I had thought to look, but when you think about it, it actually makes sense. This event can be used to intercept a paste or drag and drop operation, and lets the hander do a few things:

  • cancel the operation completely
  • change which data format will be pasted from the clipboard
  • replace the DataObject used in the paste operation

In my case, I just wanted to prevent an image from being pasted or drag and dropped, so I just cancelled the operation when the FormatToApply was "Bitmap", as shown below.

XAML:

<RichTextBox DataObject.Pasting="RichTextBox1_Pasting" ... />

Code-behind:

private void RichTextBox1_Pasting(object sender, DataObjectPastingEventArgs e)
{
    if (e.FormatToApply == "Bitmap")
    {
        e.CancelCommand();
    }
}

Of course, it’s also possible to handle this in a smarter way. For instance, if the DataObject contains several formats, we could create a new DataObject with only the acceptable formats. This way the user is still able to paste something, if not the image.

Posted in WPF. Tags: , , , , . 2 Comments »

C# Puzzle 2

Very poorPoorAverageGoodExcellent (No Ratings Yet) 
Loading...Loading...

Just another little puzzle based on an issue I had at work…

Consider this piece of code :

Console.WriteLine($"x > y is {x > y}");
Console.WriteLine($"!(x <= y) is {!(x <= y)}");

How would you declare and initialize x and y for the program to produce the following, apparently illogical, output?

x > y is False
!(x <= y) is True
Posted in Puzzles. Tags: , . 2 Comments »

How to retrieve dates as UTC in SQLite

Very poorPoorAverageGoodExcellent (No Ratings Yet) 
Loading...Loading...

SQLite is a nice in-process database engine: it’s very lightweight, doesn’t require any server or configuration, and runs on all platforms. There is even an official ADO.NET provider that’s very well made. However, if you store dates as UTC with this provider, you will probably encounter a serious issue: even though the date is properly stored as UTC (it’s stored in a form similar to ISO8601, with a ‘Z’ to indicate the UTC timezone), when you read it back from the database, you will get a DateTime converted to local time, with Kind = Unspecified. Here’s an example that exhibits the problem (using Dapper in LINQPad):

void Main()
{
    string connectionString = @"Data Source=D:\tmp\testSQLiteDate.db";
    using (var connection = new SQLiteConnection(connectionString))
    {
        connection.Open();
        connection.Execute("create table Foo(Id integer not null primary key, CreationDateUtc datetime not null)");
        
        var foo = new Foo{Id = 42, CreationDateUtc = DateTime.UtcNow};
        foo.Dump("Original object");
        connection.Execute("insert into Foo(Id, CreationDateUtc) values (@Id, @CreationDateUtc)", foo);
        var foo2 = connection.Query<Foo>("select * from Foo where Id = @Id", new{ Id = 42 }).SingleOrDefault();
        foo2.Dump("After reading from DB");
    }
}

class Foo
{
    public int Id { get; set; }
    public DateTime CreationDateUtc { get; set; }
    public DateTimeKind Kind { get { return CreationDateUtc.Kind; } }
}

Here’s the output:

image

As you can see, after reading it from the database, the date is no longer in UTC, and doesn’t even contain an indication that it’s a local date. This can cause all kinds of bugs if your code is comparing dates that are supposed to be UTC.

I initially tried to fix that in my code by manually converting the date, before I realized that the solution was much simpler (although not very well documented): there is a connection string setting to control how dates are handled. You just need to specify DateTimeKind=Utc in your connection string:

string connectionString = @"Data Source=D:\tmp\testSQLiteDate.db;DateTimeKind=Utc";

If you’re using SqliteConnectionStringBuilder to build the connection string, just set the DateTimeKind property to DateTimeKind.Utc.

As you can see, the date kind is now preserved:

image

 

Important caveat: this setting will apply to all dates read from this connection. If you have dates that were not stored as UTC, the provider will assume that they are UTC dates anyway, which will produce incorrect results. So, only do this if you store all dates as UTC.

Create an auto-mocking container with Unity and FakeItEasy

Very poorPoorAverageGoodExcellent (No Ratings Yet) 
Loading...Loading...

Unit testing can be tedious sometimes, especially when testing classes that have complex dependencies. Fortunately, some tools make it somewhat easier. I’ve been using FakeItEasy a lot recently; it’s a very easy to use mocking framework for .NET. It has a very lean and simple API based on generics and lambda expressions, and is a real pleasure to work with. It came as a breath of fresh air compared to the old RhinoMocks I had been using before.

But as nice as FakeItEasy is, the process of registering all the fake dependencies for the class you are testing is still a bit tedious. Wouldn’t it be nice if the IoC container could automatically create the fakes on demand ? So this code:

var container = new UnityContainer();

// Setup dependencies
var fooProvider = A.Fake<IFooProvider>();
container.RegisterInstance(fooProvider);
var barService = A.Fake<IBarService>();
container.RegisterInstance(barService);
var bazManager = A.Fake<IBazManager>();
container.RegisterInstance(bazManager);

var sut = container.Resolve<SystemUnderTest>();

Could be reduced to this:

var container = new UnityContainer();

// This will cause the container to provide fakes for all dependencies
container.AddNewExtension<AutoFakeExtension>();

var sut = container.Resolve<SystemUnderTest>();

Well, it’s actually pretty easy to do with Unity. Unity is usually not considered the “cool kid” in the small world of IoC containers, but it’s well supported, easy to use, and extensible. I came up with the following extension to enable the above scenario:

public class AutoFakeExtension : UnityContainerExtension
{
    protected override void Initialize()
    {
        Context.Strategies.AddNew<AutoFakeBuilderStrategy>(UnityBuildStage.PreCreation);
    }
    
    private class AutoFakeBuilderStrategy : BuilderStrategy
    {
        private static readonly MethodInfo _fakeGenericDefinition;
    
        static AutoFakeBuilderStrategy()
        {
            _fakeGenericDefinition = typeof(A).GetMethod("Fake", Type.EmptyTypes);
        }
        
        public override void PreBuildUp(IBuilderContext context)
        {
            if (context.Existing == null)
            {
                var type = context.BuildKey.Type;
                if (type.IsInterface || type.IsAbstract)
                {
                    var fakeMethod = _fakeGenericDefinition.MakeGenericMethod(type);
                    var fake = fakeMethod.Invoke(null, new object[0]);
                    context.PersistentPolicies.Set<ILifetimePolicy>(new ContainerControlledLifetimeManager(), context.BuildKey);
                    context.Existing = fake;
                    context.BuildComplete = true;
                }
            }
            base.PreBuildUp(context);
        }
    }
}

A few comments on this code:

  • The logic is a bit crude (it generates fakes only for interfaces and abstract classes), but can easily be adjusted if necessary.
  • The ugly reflection hack is due to the fact that FakeItEasy doesn’t have an non-generic overload of A.Fake that accepts a Type as a parameter. Well, nobody’s perfect…
  • The lifetime is set to “container controlled”, because if you need to configure method calls, you will need to access the same instance that is injected into the system under test:
var fooProvider = container.Resolve<IFooProvider>();
A.CallTo(() => fooProvider.GetFoo(42)).Returns(new Foo { Id = 42, Name = “test” });

Note that if you register a dependency explicitly, it will take precedence and no fake will be created. So you can use this extension and still be able to manually specify a dependency:

var container = new UnityContainer();
container.AddNewExtension<AutoFakeExtension>();
container.RegisterType<IFooProvider, TestFooProvider>();
var sut = container.Resolve<SystemUnderTest>();

Of course, this extension could easily be modified to use a different mocking framework. I guess the same principle could be applied to other IoC containers as well, as long as they have suitable extension points.

What about AutoFixture?

Before you ask: yes, I know about AutoFixture. It’s a pretty good library, and I actually tried to use it as well, with some success. The resulting code is very similar to the examples above. The main reason why I didn’t keep using it is that AutoFixture is not really an IoC container (though it does some of the things an IoC container does), and I prefer to use the same IoC mechanism in my unit tests and in the actual application. Also, I’m not very comfortable with the way it handles properties when creating an instance of the SUT. By default, it sets all public writable properties to dummy instances of their type; this is fine if those properties are used for dependency injection, but IMO it doesn’t make sense for other properties. I know I can suppress this behavior for specific properties, but I have to do it manually on a case by case basis; it doesn’t take IoC container specific attributes like [Dependency] into account. So eventually I found it easier to use my custom Unity extension.

Async and cancellation support for wait handles

Very poorPoorAverageGoodExcellent (2 votes) 
Loading...Loading...

The .NET framework comes with a number of low-level synchronization primitives. The most commonly used are collectively known as “wait handles”, and inherit the WaitHandle class: Semaphore, Mutex, AutoResetEvent and ManualResetEvent. These classes have been there since at least .NET 2.0 (1.1 for some of them), but they haven’t evolved much since they were introduced, which means they don’t support common features that were introduced later. In particular, they don’t provide support for waiting asynchronously, nor do they support cancelling the wait. Fortunately, it’s actually quite easy to add these features via extension methods.

Cancellation

Let’s start with the easiest one: cancellation. There are cases where it would be useful to pass a CancellationToken to WaitHandle.WaitOne, but none of the overloads supports it. Note that some more recent variants of the synchronization primitives, such as SemaphoreSlim and ManualResetEventSlim, do support cancellation; however, they’re not necessarily suitable for all use cases, because they’re designed for when the wait times are expected to be very short.

A CancellationToken exposes a WaitHandle, which is signaled when cancellation is requested. We can take advantage of this to implement a cancellable wait on a wait handle:

    public static bool WaitOne(this WaitHandle handle, int millisecondsTimeout, CancellationToken cancellationToken)
    {
        int n = WaitHandle.WaitAny(new[] { handle, cancellationToken.WaitHandle }, millisecondsTimeout);
        switch (n)
        {
            case WaitHandle.WaitTimeout:
                return false;
            case 0:
                return true;
            default:
                cancellationToken.ThrowIfCancellationRequested();
                return false; // never reached
        }
    }

We use WaitHandle.WaitAny to wait for either the original wait handle or the cancellation token’s wait handle to be signaled. WaitAny returns the index of the first wait handle that was signaled, or WaitHandle.WaitTimeout if a timeout occurred before any of the wait handles was signaled. So we can have 3 possible outcomes:

  • a timeout occurred: we return false (like the standard WaitOne method);
  • the original wait handle is signaled first: we return true (like the standard WaitOne method);
  • the cancellation token’s wait handle is signaled first: we throw an OperationCancelledException.

    For completeness, let’s add some overloads for common use cases:

        public static bool WaitOne(this WaitHandle handle, TimeSpan timeout, CancellationToken cancellationToken)
        {
            return handle.WaitOne((int)timeout.TotalMilliseconds, cancellationToken);
        }
        
        public static bool WaitOne(this WaitHandle handle, CancellationToken cancellationToken)
        {
            return handle.WaitOne(Timeout.Infinite, cancellationToken);
        }
    

    And that’s it, we now have a cancellable WaitOne method!

    Asynchronous wait

    Now, what about asynchronous wait? That’s a bit harder. What we want here is a WaitOneAsync method that returns a Task<bool> (and since we’re at it, we might as well include cancellation support). The typical approach to create a Task wrapper for a non-task-based asynchronous operation is to use a TaskCompletionSource<T>, so that’s what we’ll do. When the wait handle is signaled, we’ll set the task’s result to true; if a timeout occurs, we’ll set it to false; and if the cancellation token is signaled, we’ll mark the task as cancelled.

    I struggled a bit to find a way to execute a delegate when a wait handle is signaled, but I eventually found the ThreadPool.RegisterWaitForSingleObject method, which exists for this exact purpose. I’m not sure why it’s in the ThreadPool class; I think it would have made more sense to put it in the WaitHandle class, but I assume there’s a good reason.

    So here’s what we’ll do:

  • create a TaskCompletionSource<bool>;
  • register a delegate to set the result to true when the wait handle is signaled, or false if a timeout occurs, using ThreadPool.RegisterWaitForSingleObject;
  • register a delegate to mark the task as cancelled when the cancellation token is signaled, using CancellationToken.Register;
  • unregister both delegates after the task completes

    Here’s the implementation:

        public static async Task<bool> WaitOneAsync(this WaitHandle handle, int millisecondsTimeout, CancellationToken cancellationToken)
        {
            RegisteredWaitHandle registeredHandle = null;
            CancellationTokenRegistration tokenRegistration = default(CancellationTokenRegistration);
            try
            {
                var tcs = new TaskCompletionSource<bool>();
                registeredHandle = ThreadPool.RegisterWaitForSingleObject(
                    handle,
                    (state, timedOut) => ((TaskCompletionSource<bool>)state).TrySetResult(!timedOut),
                    tcs,
                    millisecondsTimeout,
                    true);
                tokenRegistration = cancellationToken.Register(
                    state => ((TaskCompletionSource<bool>)state).TrySetCanceled(),
                    tcs);
                return await tcs.Task;
            }
            finally
            {
                if (registeredHandle != null)
                    registeredHandle.Unregister(null);
                tokenRegistration.Dispose();
            }
        }
        
        public static Task<bool> WaitOneAsync(this WaitHandle handle, TimeSpan timeout, CancellationToken cancellationToken)
        {
            return handle.WaitOneAsync((int)timeout.TotalMilliseconds, cancellationToken);
        }
        
        public static Task<bool> WaitOneAsync(this WaitHandle handle, CancellationToken cancellationToken)
        {
            return handle.WaitOneAsync(Timeout.Infinite, cancellationToken);
        }
    

    Note that the lambda expressions could have used the tcs variable directly; this would make the code more readable, but it would cause a closure to be created, so as a small performance optimization, tcs is passed as the state parameter.

    We can now use the WaitOneAsync method like this:

    var mre = new ManualResetEvent(false);
    …
    if (await mre.WaitOneAsync(2000, cancellationToken))
    {
        …
    }
    

    Important note: this method will not work for a Mutex, because it relies on RegisterWaitForSingleObject, which is documented to work only on wait handles other than Mutex.

    Conclusion

    We saw that with just a few extension methods, we made the standard synchronization primitives much more usable in typical modern code involving asynchrony and cancellation. However, I can hardly finish this post without mentioning Stephen Cleary’s AsyncEx library; it’s a rich toolbox which offers async-friendly versions of most standard primitives, some of which will let you achieve the same result as the code above. I encourage you to have a look at it, there’s plenty of good stuff in it.

  • Posted in Code sample. Tags: , , . 4 Comments »

    C# Puzzle 1

    Very poorPoorAverageGoodExcellent (7 votes) 
    Loading...Loading...

    I love to solve C# puzzles; I think it’s a great way to gain a deep understanding of the language. And besides, it’s fun!

    I just came up with this one:

    static void Test(out int x, out int y)
    {
        x = 42;
        y = 123;
        Console.WriteLine (x == y);
    }
    

    What do you think this code prints? Can you be sure? Post your answer in the comments!

    I’ll try to post more puzzles in the future if I can come up with others.

    Posted in Puzzles. Tags: , . 12 Comments »

    Async unit tests with NUnit

    Very poorPoorAverageGoodExcellent (No Ratings Yet) 
    Loading...Loading...

    Recently, my team and I started writing unit tests on an application that uses a lot of async code. We used NUnit (2.6) because we were already familiar with it, but we had never tried it on async code yet.

    Let’s assume the system under test is this very interesting Calculator class:

        public class Calculator
        {
            public async Task<int> AddAsync(int x, int y)
            {
                // simulate long calculation
                await Task.Delay(100).ConfigureAwait(false);
                // the answer to life, the universe and everything.
                return 42;
            }
        }
    

    (Hint: this code has a bug… 42 isn’t always the answer. This came to me as a shock!)

    And here’s a unit test for the AddAsync method:

            [Test]
            public async void AddAsync_Returns_The_Sum_Of_X_And_Y()
            {
                var calculator = new Calculator();
                int result = await calculator.AddAsync(1, 1);
                Assert.AreEqual(2, result);
            }
    

    async void vs. async Task

    Even before trying to run this test, I thought to myself: This isn’t gonna work! an async void method will return immediately on the first await, so NUnit will think the test is complete before the assertion is executed, and the test will always pass even if the assertion fails. So I changed the method signature to async Task instead, thinking myself very clever for having avoided this trap…

            [Test]
            public async Task AddAsync_Returns_The_Sum_Of_X_And_Y()
    
    

    As expected, the test failed, confirming that NUnit knew how to handle async tests. I fixed the Calculator class, and stopped thinking about it. Until one day, I noticed that my colleague was writing test methods with async void. So I started to explain to him why it couldn’t work, and tried to demonstrate it by introducing an assertion that would fail… and to my surprise, the test failed, proving that I was wrong. Mind blown!

    Having an inquisitive mind, I immediately started to investigate… My first idea was to check the current SynchronizationContext, and indeed I saw that NUnit had changed it to an instance of NUnit.Framework.AsyncSynchronizationContext. This class maintains a queue of all the continuations that are posted to it. After the async void test method has returned (i.e., the first time a not-yet-completed task is awaited), NUnit calls the WaitForPendingOperationsToComplete method, which executes all the continuations in the queue, until the queue is empty. Only then is the test considered complete.

    So, the moral of the story is: you can write async void unit tests in NUnit 2.6. It also works for delegates passed to Assert.Throws, which can have an async modified. Now, just because you can doesn’t mean you should. Not all test frameworks seem to have the same support for this. The next version of NUnit (3.0, still in alpha) will not support async void tests.

    So, unless you plan on staying with NUnit 2.6.4 forever, it’s probably better to always use async Task in your unit tests.

    Posted in Unit testing. Tags: , , , . 2 Comments »
    css.php