4

当您在控制器中使用 Async/Await 时,您是否必须从 AsyncController 继承,或者如果您使用 Controller,它是否真的不是异步的?Asp.net web api怎么样?我认为没有 AsyncApiController。目前我只是从控制器继承及其工作,但它真的是异步的吗?

4

2 回答 2

6

AsyncControllerMVC 4中类的 XML 注释说

提供与 ASP.NET MVC 3 的向后兼容性。

类本身是空的。

换句话说,你不需要它。

于 2012-10-24T17:37:08.747 回答
0

就 Web API 而言,您不需要 Async 控制器基类。您需要做的就是将返回值包装在一个任务中。

例如,

    /// <summary>
    /// Assuming this function start a long run IO task
    /// </summary>
    public Task<string> WorkAsync(int input)
    {
        return Task.Factory.StartNew(() =>
            {
                // heavy duty here ...

                return "result";
            }
        );
    }

    // GET api/values/5
    public Task<string> Get(int id)
    {
        return WorkAsync(id).ContinueWith(
            task =>
            {
                // disclaimer: this is not the perfect way to process incomplete task
                if (task.IsCompleted)
                {
                    return string.Format("{0}-{1}", task.Result, id);
                }
                else
                {
                    throw new InvalidOperationException("not completed");
                }
            });
    }

此外,在 .Net 4.5 中,您可以从 await-async 中受益,编写更简单的代码:

    /// <summary>
    /// Assuming this function start a long run IO task
    /// </summary>
    public Task<string> WorkAsync(int input)
    {
        return Task.Factory.StartNew(() =>
            {
                // heavy duty here ...

                return "result";
            }
        );
    }

    // GET api/values/5
    public async Task<string> Get(int id)
    {
        var retval = await WorkAsync(id);

        return string.Format("{0}-{1}", retval, id);
    }
于 2012-10-24T20:30:57.203 回答