我对异步/等待的理解是否正确?

Tri*_*rue 0 c# asp.net asp.net-mvc asynchronous async-await

根据我的理解,下面的代码最终应该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;
}
Run Code Online (Sandbox Code Playgroud)

这应该与Matthew Jones的文章中的代码相同

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;
}
Run Code Online (Sandbox Code Playgroud)

但是我收到错误await classification:'string'不包含'GetAwaiter'的定义

我不确定为什么会这样.

另外,根据MSDN文档进行昂贵的计算,我应该使用:

property.ClassificationCode = await Task.Run(() => GetClassification(property));
Run Code Online (Sandbox Code Playgroud)

这实际上是实现了我想要的还是只是同步运行?

在此先感谢您的帮助.

Mar*_*ell 7

string classification = GetClassification(property);
Run Code Online (Sandbox Code Playgroud)

这是常规同步代码; classification在分配之前它什么都不做.这听起来像你想要的是:

Task<string> classification = GetClassificationAsync(property);
Run Code Online (Sandbox Code Playgroud)

在那里GetClassificationAsync做了真正的异步中间和最终填充一个Task<string>.请注意,如果GetClassificationAsync仍然同步工作,代码将继续保持同步.特别是,如果你发现自己使用Task.FromResult:你可能没有做任何事情async.

  • 那个`GetClassification`的返回类型怎么样?不应该是`Task <string>` (2认同)
  • @Shyju如果你的意思是'GetClassificationAsync` - 那么是的,它应该是 (2认同)
  • 如果GetClassification只是CPU绑定,则不应使其异步,而是使用Task.Run => https://blog.stephencleary.com/2013/11/taskrun-etiquette-examples-even-in在最高级别调用它. HTML (2认同)