【发布时间】:2018-04-27 15:44:42
【问题描述】:
据我了解,下面的代码最终应该在运行其他代码时检索字符串classification。
[HttpPost]
public async Task<ActionResult> CreatePropertyAsync(Property property)
{
string classification = GetClassification(property);
// GetClassification() runs a complex calculation but we don't need
// the result right away so the code can do other things here related to property
// ... code removed for brevity
property.ClassificationCode = await classification;
// all other code has been completed and we now need the classification
db.Properties.Add(property);
db.SaveChanges();
return RedirectToAction("Details", new { id = property.UPRN });
}
public string GetClassification(Property property)
{
// do complex calculation
return classification;
}
这应该与Matthew Jones' article的以下代码中的工作方式相同
public async Task<string> GetNameAndContent()
{
var nameTask = GetLongRunningName(); //This method is asynchronous
var content = GetContent(); //This method is synchronous
var name = await nameTask;
return name + ": " + content;
}
但是我在await classification 上收到错误:“字符串”不包含“GetAwaiter”的定义
我不确定为什么会这样。
此外,根据MSDN docs 的昂贵计算,我应该改为使用:
property.ClassificationCode = await Task.Run(() => GetClassification(property));
这真的实现了我想要的,还是只是同步运行?
提前感谢您的帮助。
【问题讨论】:
-
几个小时前的类似问题可能有助于您的理解:stackoverflow.com/q/47285836/23354
-
请注意,MSDN 页面与 ASP.NET 无关。
-
你对 async/awat 的理解是错误的,但更严重的是你对服务器端编程的理解也是有缺陷的。对于异步 I/O,追加到等待链。对于 CPU 密集型工作,什么都不做或做对:hanselman.com/blog/HowToRunBackgroundTasksInASPNET.aspx
标签: c# asp.net asp.net-mvc asynchronous async-await