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

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

问题描述

我有,需要一个回调参数异步执行的方法,但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);
}

有没有办法赶上了新的线程抛出的异常,并将其发送到原来的线程?此外,这是正确的方式来处理异步异常?我写我的code,以便它可以这样调用(假设异常的问题是固定的):

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

这样,您将检查结果对象,看它是否有结果,或者例外字段集,并采取相应的行动。

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天全站免登陆