当你在你的控制器中使用Async/Await时,你必须从AsyncController继承吗?或者如果你使用控制器,它是否真的不是异步的?Asp.net网络应用程序接口怎么样?我不认为有AsyncApiController。目前我只是继承了控制器和它的工作方式,但是它真的是异步的吗?
发布于 2012-10-25 01:37:09
MVC4中AsyncController类的XML注释如下
提供了与ASP.NET MVC3的向后兼容性。
类本身是空的。
换句话说,你不需要它。
发布于 2012-10-25 04:30:57
就Web API而言,您不需要异步控制器基类。您所需要做的就是将返回值包装在一个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);
}https://stackoverflow.com/questions/13054626
复制相似问题