我在哪里处理异步异常? [英] Where do I handle asynchronous exceptions?

查看:160
本文介绍了我在哪里处理异步异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下代码:

  class Foo {
//无节省的零件

private TcpClient socket;

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

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

如果套接字 BeginConnect 后引发异常返回并在 cbConnect 被调用之前,它在哪里弹出?是否允许在后台投掷?

解决方案

来自 msdn论坛。我觉得,对于TcpClient模式将是一样的。

  using System; 
使用System.Runtime.Remoting.Messaging;

类程序{
static void Main(string [] args){
new Program()。
Console.ReadLine();
}
void Run(){
Action example = new Action(threaded);
IAsyncResult ia = example.BeginInvoke(new AsyncCallback(completed),null);
//选项#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){
//选项#2:
动作示例=(ar as AsyncResult).AsyncDelegate as Action;
try {
example.EndInvoke(ar);
}
catch(Exception ex){
Console.WriteLine(ex.Message);
}
}
}


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? Is it even allowed to throw in the background?

解决方案

Code sample of exception handling for asynch delegate from msdn forum. I beleive that for TcpClient pattern will be the same.

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);
    }
  }
}

这篇关于我在哪里处理异步异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆