如何修复捕获 TimeoutException?

How to fix catching TimeoutException?

我怎样才能赶上TimeoutException

我想在 3 秒后赶上 TimeoutException。 但 3 秒后它打印出 TimeoutExceptionIt's too long. Timeout! 是预期的。

使用 console application 它不会捕获 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 : ~~~");
}

您可能捕获了错误的异常。根据 Microsoft 文档 (https://docs.microsoft.com/fr-fr/dotnet/api/system.timeoutexception?view=netframework-4.8),您应该捕获 TimeOutException class.

正如其他人所说,您没有捕捉到良好的异常。但这不是预期的答案,因为一个线程的错误无法从另一个线程捕获。

有几种处理这种情况的方法,可以在answer中找到。

您的案例示例:

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);
    }
}