【问题标题】:Async/Await & AsyncController?异步/等待和异步控制器?
【发布时间】:2012-10-14 19:30:00
【问题描述】:

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

【问题讨论】:

标签: asp.net .net asp.net-mvc asp.net-web-api async-await


【解决方案1】:

MVC 4 中 AsyncController 类的 XML 注释说

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

类本身是空的。

换句话说,你不需要它。

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2018-03-12
      • 1970-01-01
      • 2023-03-12
      • 2012-12-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多