我在哪里处理异步exception?

请考虑以下代码:

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返回之后并且在调用BeginConnect之前抛出exception,它会弹出哪里? 它甚至被允许扔在后台吗?

来自msdn论坛的 asynch委托的exception处理代码示例。 我相信,对于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); } } } 

如果接受连接的过程导致错误,则将调用cbConnect方法。 要完成连接,您需要进行以下呼叫

 socket.EndConnection(result); 

此时,BeginConnect进程中的错误将显示在抛出的exception中。