Gyö*_*sek 9 .net c# asynchronous exception-handling
请考虑以下代码:
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
}
}
Run Code Online (Sandbox Code Playgroud)
如果socket在BeginConnect返回之后抛出异常并且在cbConnect调用之前抛出异常,它会在哪里弹出?甚至允许扔在后台?
来自msdn论坛的 asynch委托的异常处理代码示例.我相信,对于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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5955 次 |
| 最近记录: |