Testing asynchronous methods in .NET (or, how to make an async method synchronous)

/ Published in: C#
Save to your folder(s)

Since an asynchronous method is usually one you call and then it invokes a callback when it is finished, it is not obvious how to test such a method in a definite manner. In the method described at the above URL, the author uses .NET's System.Threading.AutoResetEvent, along with a member variable, to notify the primary thread that the test method has finished. The source below (from Radiant::Mirage::Empire) tests a method called ReadVersion from an API which fires events at the completion of each command or a special event if there is an error. The static constructor initializes the API, subscribes to the Error event, and adds Trace output to the Console. The two event listeners simply log data (to Trace or to a member variable) and then set the AutoResetEvent so that the calling method can proceed. AsyncTest is a method that allows me to call a method and then perform the same, standard procedures afterwards (creating the AutoResetEvent, waiting for the thread to return, and outputting to Trace). The actual test method, ReadVersionTest, calls AsyncTest with a lambda (which is an anonymous method that gets called inside AsyncTest) that subscribes to the relevant event and issues the specified command. The ReadVersionTestComplete method shows what the code would look like without using the AsyncTest method and lambda.

URL: http://jasondotnet.spaces.live.com/blog/cns!BD40DBF53845E64F!170.entry

Report this snippet


RSS Icon Subscribe to comments

You need to login to post a comment.