Search code examples
c#exceptiontimeout

Timeout Exception


my code looks somewhat like this:

    try
    {
        return myClass.doSomethind();
    }
    catch (Exception ex)
    {
        Result emptyResult = new Result();
        return emptyResult;
    }

myClass is one of 15 inherited classes from myClassBase. So far the exception handling works. If in myClass.doSomething() an exception is thrown it ends up in the catch block. Now I want to add something like a Timeout Exception, which is thrown, when myClass.doSomething() takes to long. The following code doesn't work, since the thrown exception is not propagated to the try block.

    try
    {
        System.Timers.Timer TimeoutTimer = new System.Timers.Timer(10000); 
        TimeoutTimer.AutoReset = false;
        TimeoutTimer.Elapsed += TimeoutErrorEventHandler;
        TimeoutTimer.Enabled = true;
        return myClass.doSomethind();
    }
    catch (Exception ex)
    {
        Result emptyResult = new Result();
        return emptyResult;
    }

static void TimeoutErrorEventHandler(Object source, System.Timers.ElapsedEventArgs e)
{
    throw new Exception("Timeout")
}

What would be the best way to solve this problem?

Thank you for your help


Solution

  • You may try this:

    try
    {
        System.Timers.Timer TimeoutTimer = new System.Timers.Timer(10000); 
        TimeoutTimer.AutoReset = false;
        TimeoutTimer.Elapsed += TimeoutErrorEventHandler;
        TimeoutTimer.Enabled = true;
        Task<Result> doSomethingTask = Task.Run (() => myClass.doSomethind());
        if (doSomethingTask.Wait(10000) 
        {
           return doSomethingTask.Result;  
        }
        else 
        {
            Result emptyResult = new Result();
            return emptyResult;
        }
    }
    catch (Exception ex)
    {
        Result emptyResult = new Result();
        return emptyResult;
    }