我在哪里可以处理异步异常

我在哪里可以处理异步异常

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

问题描述

考虑以下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
    }
}

如果插槽 BeginConnect 收益和 cbConnect 被调用,在它弹出?它甚至允许抛出的背景是什么?

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异常的样品处理的异步委托从msdn论坛。我beleive对于TcpClient的图案将是相同的。

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

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

07-24 10:59