Warning : This page has been marked as an archive because the author consider that its content is no longer relevant.
One recurring problem when we create an application using asynchronous calls is to test this asynchronism. We want to verify the behavior of our application if an operation take 10 seconds or 1 minute to complete.
Let’s take a simple exemple.
We have the MyAsyncMethod method which notifies the end of its execution by raising then MyAsyncMethodCompleted event. We want to simulate a 5 second latency on this method.
Here’s the code allowing us to do that :
public void MyAsyncMethod()
{
Timer timer = null;
var context = SynchronizationContext.Current;
TimerCallback c = state =>
{
if (timer != null)
timer.Dispose();
context.Post(o => MyAsyncMethodCompleted(this, null));
};
timer = new Timer(c, null, 5000, int.MaxValue);
}
The idea is to create a time that will be waiting 5 seconds to invoke a callback. This callback will dispose the timer and invoke the completed event. The main issue here is that the timer will invoke its callback in another thread than the one which initiated the call. In order to call back on the right thread we saved the synchronisation context in a variable. Then, we post the call of the completed event to the synchronisation context. This is like the Dispatcher.BeginInvoke for Silverlight or WPF but here it works for any threads.
So in the end, for the calling method everything is transparent and we introduced latency.
Simple and useful :-)
Comments