2012-10-24 364 views
4

當您在控制器中使用Async/Await時,是否必須從AsyncController繼承,或者如果您使用Controller,它是否真的不會異步?怎麼樣的Asp.net網絡API?我不認爲有一個AsyncApiController。目前我只是從控制器和它的工作繼承,但它真的是異步?異步/等待&AsyncController?

+0

見我的教程HTTP:// WWW。 asp.net/mvc/tutorials/mvc-4/using-asynchronous-methods-in-aspnet-mvc-4 – RickAndMSFT

回答

6

在MVC 4 AsyncController類的XML註釋說

提供向後兼容ASP.NET MVC 3

類本身是空的。

換句話說,你不需要它。

+0

感謝您的信息。 – coding4fun

0

就Web API而言,您不需要Async控制器基類。所有你需要做的就是把你的返回值包裝在一個Task中。

例如,

/// <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,你可以從等待,異步受益寫出更簡單的代碼:

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