Introducing CountdownEvent

The new .NET 4.0 has a lot of new multi-threaded goodness, one of which is the CountdownEvent, used to signal between thread just like the good old AutoResetEvent and ManualEvent.

The big difference (as you might have already guessed) is that CountDownEvent can be used to signal after several set has been called.

The reason I’m telling you about this is because today needed to write an integration test to check communication between a client class to a server class (never mind the specifics). Here I was in the middle of an intensive TDD session and I got to a point where I needed to check if two clients send messages to the server two messages arrive at the server and he messages were asynchronous meaning that I needed to delay the test until they arrive.

Using the simple event just didn’t work so I’ve went to the place I go when I have a multi-threading question – Threading in C# Ebook which was updated to include .NET 4.0 and found about CountingEvent – and presto:

[TestMethod]
public void TwoClientsCallServer()
{
client1 = CreatClientAndConnectToServer();
client2 = CreatClientAndConnectToServer();

var countdownEvent = new CountdownEvent(2);

server.OnMessageArrived += (sender, args) => countdownEvent.Signal();

client1.SendMessage();
client2.SendMessage();

var result = countdownEvent.Wait(1000);

Assert.IsTrue(result);
}

I’m not too happy about using timeout in my tests but this is one of these times where I couldn’t find a better solution.

Being curious about how CountdownEvent works I’ve opened Reflector and did a simple investigation

image 

It’s quite simple if you read past the synchronization and the goto – it uses a wait handle (slim) and a counter (int) and it set the handle once that the counter has reached the specify number of “events”.

 

It’s awfully nice of Microsoft – implementing this class, so we won’t have to.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s