gpt4 book ai didi

c# - 我在哪里处理异步异常?

转载 作者:太空狗 更新时间:2023-10-29 17:47:22 26 4
gpt4 key购买 nike

考虑以下代码:

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 被调用之前抛出异常,它会在哪里弹出?甚至可以在后台转换吗?

最佳答案

来自 msdn forum 的异步委托(delegate)的异常处理代码示例.我相信 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);
}
}
}

关于c# - 我在哪里处理异步异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3050784/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com