如何在BeginInvoke()中捕获TimeoutException

时间:2019-07-31 07:49:30

标签: c# asynchronous begininvoke

我希望test.BeginInvoke()在时间限制后引发TimeoutException。 但是,它没有捕获TimeoutException。 我该如何解决?非常感谢。

public delegate void AasyncDelegateCaller(int callDuration, out int threadId);

public void AasyncDelegate(int callDuration, out int threadId)
{
    Thread.Sleep(callDuration);
    threadId = Thread.CurrentThread.ManagedThreadId;
    Console.WriteLine("TimeoutException");
    throw new TimeoutException();
}


private static void Search()
{
    try
    {
        int threadId;
        Program p = new Program();
        AasyncDelegateCaller caller = new AasyncDelegateCaller(p.AasyncDelegate);
        IAsyncResult result = caller.BeginInvoke(3000, out threadId, null, null);
        SearchProgram(); // Sometimes it takes a long time. So I want to throw TimeoutException at that time
    }
    catch (TimeoutException)
    {
        Console.WriteLine("It takes Long! Bye");
    }

}

0 个答案:

没有答案