捕获异步回调中抛出的异常 [英] Catching an exception thrown in an asynchronous callback

查看:27
本文介绍了捕获异步回调中抛出的异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个方法需要一个回调参数来异步执行,但 catch 块似乎没有捕获同步调用抛出的任何异常(this.Submit 指的是同步方法).

I have a method that takes a callback argument to execute asynchronously, but the catch block doesn't seem to be catching any exceptions thrown by the synchronous call (this.Submit refers to a synchronous method).

public void Submit(FileInfo file, AnswerHandler callback)
{
    SubmitFileDelegate submitDelegate = new SubmitFileDelegate(this.Submit);
    submitDelegate.BeginInvoke(file, (IAsyncResult ar) =>
    {
        string result = submitDelegate.EndInvoke(ar);
        callback(result);
    }, null);
}

有没有办法捕获新线程抛出的异常并发送给原线程?另外,这是处理异步异常的正确"方式吗?我写了我的代码,所以它可以像这样调用(假设异常问题已修复):

Is there a way to catch the exception thrown by the new thread and send it to the original thread? Also, is this the "proper" way to handle async exceptions? I wrote my code so it could be called like this (assuming the exception issue is fixed):

try
{
    target.Submit(file, (response) =>
    {
        // do stuff
    });
}
catch (Exception ex)
{
    // catch stuff
}

但是有没有更合适或更优雅的方法来做到这一点?

but is there a more proper or elegant way to do this?

推荐答案

这不是最佳实践"解决方案,但我认为这是一个应该可行的简单解决方案.

This is not a 'best practice' solution, but I think it's a simple one that should work.

而不是将委托定义为

private delegate string SubmitFileDelegate(FileInfo file);

定义为

private delegate SubmitFileResult SubmitFileDelegate(FileInfo file);

并定义 SubmitFileResult 如下:

and define the SubmitFileResult as follows:

public class SubmitFileResult
{
    public string Result;
    public Exception Exception;
}

那么,实际执行文件提交的方法(问题中未显示)应该像这样定义:

Then, the method that actually does the file submission (not shown in the question) should be defined like this:

private static SubmitFileResult Submit(FileInfo file)
{
    try
    {
        var submissionResult = ComplexSubmitFileMethod();

        return new SubmitFileResult { Result = submissionResult };
    }
    catch (Exception ex)
    {
        return new SubmitFileResult {Exception = ex, Result = "ERROR"};
    }
}

这样,您将检查结果对象,查看它是否设置了 Result 或 Exception 字段,然后采取相应的行动.

This way, you'll examine the result object, see if it has the Result or the Exception field set, and act accordingly.

这篇关于捕获异步回调中抛出的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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