O'Reilly logo

C# Cookbook by Jay Hilyard, Stephen Teilhet

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

15.5. Timing Out an Asynchronous Delegate

Problem

You want an asynchronous delegate to operate only within an allowed time span. If it is not finished processing within this time frame, the operation will time out. If the asynchronous delegate times out, it must perform any cleanup before the thread it is running on is terminated.

Solution

The WaitHandle.WaitOne method can indicate when an asynchronous operation times out. The code on the invoking thread needs to periodically wake up to do some work along with timing-out after a specific period of time. Use the approach shown in the following code, which will wake up every 20 milliseconds to do some processing. This method also times out after a specific number of wait/process cycles (note that this code will actually time out after more than two seconds of operation since work is being done between the wait cycles):

public class AsyncAction { public void TimeOutWakeAsyncDelegate( ) { AsyncInvoke method1 = new AsyncInvoke(TestAsyncInvoke.Method1); // Define the AsyncCallback delegate to catch EndInvoke if we timeout. AsyncCallback callBack = new AsyncCallback(TestAsyncInvoke.CallBack); // Set up the BeginInvoke method with the callback and delegate IAsyncResult asyncResult = method1.BeginInvoke(callBack,method1); int counter = 0; while (counter <= 25 && !asyncResult.AsyncWaitHandle.WaitOne(20, true)) { counter++; Console.WriteLine("Processing..."); } if (asyncResult.IsCompleted) { int retVal = method1.EndInvoke(asyncResult); Console.WriteLine("retVal ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required