[英]Where do I handle asynchronous exceptions?
Consider the following code: 请考虑以下代码:
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
}
}
If socket
throws an exception after BeginConnect
returns and before cbConnect
gets called, where does it pop up? 如果
socket
抛出后异常BeginConnect
回报和前cbConnect
被调用,在它弹出? Is it even allowed to throw in the background? 甚至允许扔在后台?
Code sample of exception handling for asynch delegate from msdn forum . 来自msdn论坛的 asynch委托的异常处理代码示例。 I beleive that for TcpClient pattern will be the same.
我相信,对于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);
}
}
}
If the process of accepting a connection results in an error your cbConnect method will be called. 如果接受连接的过程导致错误,则将调用cbConnect方法。 To complete the connection though you'll need to make the following call
要完成连接,您需要进行以下呼叫
socket.EndConnection(result);
At that point the error in the BeginConnect process will be manifested in a thrown exception. 此时,BeginConnect进程中的错误将显示在抛出的异常中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.