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 ...

Get C# Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.