Search code examples
c#multithreadingtimeoutexception

How to fix catching TimeoutException?


How can I catch TimeoutException?

I want to catch TimeoutException after 3 secs. But after 3 secs it prints out TimeoutException whereas It's too long. Timeout! is expected.

With console application it doesn't catch TimeoutException.

public static void work()
{
    Thread.Sleep(3000);
    Console.WriteLine("TimeoutException");
    throw new TimeoutException();
}

public static void Main(string[] args)
{
    try
    {
        ThreadStart th = new ThreadStart(work);
        Thread t = new Thread(th);
        t.Start();
        //Execute SearchProgram
        t.Abort();
    }
    catch (ThreadInterruptedException)
    {
        Console.WriteLine("It's too long. Timeout!");
    }

    Console.WriteLine("Result : ~~~");
}

Solution

  • As others have been able to say you do not catch the good exception. But this is not the expected answer since the error of one thread can not be catched from another.

    There are several ways to handle this case, which can be found in this answer.

    An example for your case:

    public static void work()
    {
        Thread.Sleep(3000);
        Console.WriteLine("TimeoutException");
        throw new TimeoutException();
    }
    
    public static void Main(string[] args)
    {
        Thread thread = new Thread(() => SafeExecute(() => work(), Handler));
        thread.Start();
    
        Console.WriteLine("Result : ~~~");
        Console.ReadLine();
    }
    
    private static void Handler(Exception exception)
    {
        Console.WriteLine(exception);
    }
    
    private static void SafeExecute(Action test, Action<Exception> handler)
    {
        try
        {
            test.Invoke();
        }
        catch (TimeoutException ex)
        {
            Console.WriteLine("It's too long. Timeout!");
        }
        catch (Exception ex)
        {
            Handler(ex);
        }
    }