为什么我的Async方法调用异常没有被捕获

本文关键字:异常 我的 Async 方法 调用 为什么 | 更新日期: 2023-09-27 18:17:22

我认为如果我用一个try catch来包装EndInvoke调用,如果抛出一个错误,那么我的catch块会处理它吗?我一定是做错了什么?一定是用户错误,只是不确定是什么?

编辑:

当我运行这个停止应用程序时,我得到"异常未被用户代码处理"。如果我对代码进行分步执行,我就会看到这个,然后它就会进入catch块。但是,我希望catch块处理这个,而不是看到正在停止应用程序的未处理异常?

欢迎指教。

class Program
{
    static void Main(string[] args)
    {

       Action myMethod = new Action(Program.FooOneSecond);
        Go("Go Method");
        IAsyncResult tag =
            myMethod.BeginInvoke(null, "passing some state");
        try
        {
            myMethod.EndInvoke(tag);
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
        }
        string strState = (string)tag.AsyncState;
        Console.WriteLine("State When Calling EndInvoke: "
            + tag.AsyncState.ToString());

        Console.Read();
    }
    static int Work(string s) { return s.Length; throw null; }
    static void Go(string s) 
    {
        Console.WriteLine(s);
    }
    static void FooOneSecond()
    {
        // sleep for one second!
        Thread.Sleep(1000);
        // throw an exception
        throw new Exception("Exception from FooOneSecond");
    } 
}

为什么我的Async方法调用异常没有被捕获

我刚刚运行了你的代码,每次异常都会被捕获…