Operation Timeout

I’ve been looking into a way of having an operation time out using .net 1.1. I want the operation to be ‘decorated’ with the timeout code, so that it would appear to be a simple method without too much fuss.
What I came up with (having little experience with threading in .net) is the following code:

private delegate void AsyncTimeout(TimeSpan timeout);

private void Foo(TimeSpan timeout)
    IAsyncResult asyncResult = asyncMethod.BeginInvoke(timeout, new AsyncCallback(TimeoutElapsed), Thread.CurrentThread);

        // Really long process...
    catch (ThreadAbortException)
        throw new Exception("Timed out.");

private AsyncTimeout asyncMethod = new AsyncTimeout(Thread.Sleep);

private void TimeoutElapsed(System.IAsyncResult asyncResult)
    AsyncResult result = (AsyncResult)asyncResult;

    if (!result.EndInvokeCalled)

The delegate, field and method can be re-used for all methods that can timeout.
It works and works well, but on the other hand, passing a Thread object as state to another thread can’t possibly be good practice.
Can anyone help out here? How should this be done? Any best practices you can point out?


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