异步调用方法时异常的捕获

在异步调用一个方法时,由于不在一个线程内,异常的处理不同于普通同步调用,但可以在EndXXX时,使用try{}catch{}来捕获。

public static void main(string[] args)
{
    
string errorMessage = "this is error message";
    Action
<int> myWaiter = i =>
    {
        Thread.Sleep(i);
        
        
//抛出一个异常
        throw new ApplicationException(errorMessage);
    };
    
    myWaiter.BeginInvoke( ar 
=>
    {
        
try
        {
            
//在这里捕获异常
            myWaiter.EndInvode(ar);
        }
        
catch(ApplicationException exp)
        {
            Debug.Assert(exp.Message 
== errorMessage);
            Console.WriteLine(exp.ToString());
        }
    };
    
    Console.ReadKey();
}
posted @ 2009-02-24 17:20  阿牛  阅读(1859)  评论(0编辑  收藏  举报