你如何处理与ASP.net MVC的AsyncController一个例外? [英] How do you handle an exception with ASP.net MVC's AsyncController?

查看:159
本文介绍了你如何处理与ASP.net MVC的AsyncController一个例外?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我这有...

    public void FooAsync()
    {
        AsyncManager.OutstandingOperations.Increment();

        Task.Factory.StartNew(() =>
        {
            try
            {
                doSomething.Start();
            }
            catch (Exception e)
            {
                AsyncManager.Parameters["exc"] = e;
            }
            finally
            {
                AsyncManager.OutstandingOperations.Decrement();
            }
        });
    }

    public ActionResult FooCompleted(Exception exc)
    {
        if (exc != null)
        {
            throw exc;
        }

        return View();
    }

有没有传递一个异常给ASP.net一个更好的办法?

Is there a better way of passing an exception back to ASP.net?

干杯,伊恩。

推荐答案

任务将捕获的异常为您服务。如果你调用 task.Wait(),将包裹任何异常在 AggregateException 键,把它扔。

Task will catch the exceptions for you. If you call task.Wait(), it will wrap any caught exceptions in an AggregateException and throw it.

[HandleError]
public void FooAsync()
{
    AsyncManager.OutstandingOperations.Increment();
    AsyncManager.Parameters["task"] = Task.Factory.StartNew(() =>
    {
        try
        {
            DoSomething();
        }
        // no "catch" block.  "Task" takes care of this for us.
        finally
        {
            AsyncManager.OutstandingOperations.Decrement();
        }
    });
}

public ActionResult FooCompleted(Task task)
{
    // Exception will be re-thrown here...
    task.Wait();

    return View();
}

简单地增加一个 [的HandleError] 属性不够好。由于异常在不同的线程时,我们必须得到异常给ASP.NET线程,以便对它做任何事。只有当我们从正确的地方抛出的异常将 [的HandleError] 属性能够完成其工作。

Simply adding a [HandleError] attribute isn't good enough. Since the exception occurs in a different thread, we have to get the exception back to the ASP.NET thread in order to do anything with it. Only after we have the exception thrown from the right place will the [HandleError] attribute be able to do its job.

这篇关于你如何处理与ASP.net MVC的AsyncController一个例外?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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