繁体   English   中英

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

[英]Is my understanding of async/await correct?

根据我的理解,下面的代码最终应该在运行其他代码时检索字符串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文章的以下代码中的工作方式相同

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文档进行昂贵的计算,我应该改为使用:

property.ClassificationCode = await Task.Run(() => GetClassification(property));

这实际上实现了我想要的功能,还是无论如何都只是同步运行?

在此先感谢您的帮助。

string classification = GetClassification(property);

这是常规的同步代码; 除非分配了classification否则它将什么都不做。 听起来您想要的是:

Task<string> classification = GetClassificationAsync(property);

其中, GetClassificationAsync在中间执行一些真正异步的操作,并最终填充Task<string> 请注意,如果GetClassificationAsync仍然可以同步工作,则代码将继续保持同步。 特别地,如果您发现自己使用Task.FromResult :您可能没有做任何async

要与Matthew Jones的代码相同,您必须将代码更改为

[HttpPost]
public async Task<ActionResult> CreatePropertyAsync(Property property)
{
    Task<string> classificationTask = Task.Run( () => 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 classificationTask;
    // 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;
}

但是请阅读https://blog.stephencleary.com/2013/11/taskrun-etiquette-examples-dont-use.html为什么不使用ASP.NET

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM