2010-06-16 143 views
8

考虑下面的代码:我在哪里处理异步异常?

class Foo { 
    // boring parts omitted 

    private TcpClient socket; 

    public void Connect(){ 
     socket.BeginConnect(Host, Port, new AsyncCallback(cbConnect), quux); 
    } 

    private void cbConnect(IAsyncResult result){ 
      // blah 
    } 
} 

如果socketBeginConnect返回抛出异常之前cbConnect被调用,在它弹出?它甚至被允许抛出背景吗?

回答

7

来自msdn forum的异步委托异常处理的代码示例。我相信对于TcpClient模式将是相同的。

using System; 
using System.Runtime.Remoting.Messaging; 

class Program { 
    static void Main(string[] args) { 
    new Program().Run(); 
    Console.ReadLine(); 
    } 
    void Run() { 
    Action example = new Action(threaded); 
    IAsyncResult ia = example.BeginInvoke(new AsyncCallback(completed), null); 
    // Option #1: 
    /* 
    ia.AsyncWaitHandle.WaitOne(); 
    try { 
     example.EndInvoke(ia); 
    } 
    catch (Exception ex) { 
     Console.WriteLine(ex.Message); 
    } 
    */ 
    } 

    void threaded() { 
    throw new ApplicationException("Kaboom"); 
    } 

    void completed(IAsyncResult ar) { 
    // Option #2: 
    Action example = (ar as AsyncResult).AsyncDelegate as Action; 
    try { 
     example.EndInvoke(ar); 
    } 
    catch (Exception ex) { 
     Console.WriteLine(ex.Message); 
    } 
    } 
} 
+0

请注意,选项#1将阻止线程,直到动作完成。你也可以同步调用该方法。选项2是去这里的路... – Marc 2013-09-08 11:59:43

3

如果接受连接的过程导致错误,则将调用cbConnect方法。为了完成连接,虽然你需要做以下电话

socket.EndConnection(result); 

此时在BeginConnect过程中的误差会抛出异常表现出来。