简体   繁体   English

如何在C#中正确使用Async Await函数

[英]How do I use the Async Await functions in C# correctly

I'm still having trouble understanding how to use Async methods. 我仍然无法理解如何使用异步方法。 I have the following code in a controller. 我在控制器中有以下代码。

[HttpPost]
public async Task<IActionResult> ManualUpload([Bind("MktRpt")] ManualMktRptFileUpload itemFileUpload)
{
    var manager = new RecyclableMemoryStreamManager();
    using (var stream = manager.GetStream())
    {
       await itemFileUpload.MktRpt.CopyToAsync(stream);
       await _azureStorageService.saveBlob(stream, Path.GetFileName(itemFileUpload.MktRpt.FileName));
    }

    itemFileUpload.status = "Success";
    return View(itemFileUpload);
}

my service method is simple too: 我的服务方法也很简单:

public async Task saveBlob(MemoryStream stream, string filename)
{
    var blockBlob = _container.GetBlockBlobReference(filename);
    await blockBlob.UploadFromStreamAsync(stream);
}

along with a simple model class: 以及一个简单的模型类:

public class ManualMktRptFileUpload
{
    [Required]
    [Display(Name = "Manual Report")]
    public IFormFile MktRpt { get; set; }

    public string status { get; set; } = "Constructed";
}

When I check my Blob Container in Azure, the file is there BUT, it's zero bytes. 当我在Azure中检查我的Blob容器时,文件在那里,但是为零字节。

I believe this is because I am not correctly waiting for the stream to transfer, but I don't know how to fix it. 我相信这是因为我没有正确地等待流传输,但是我不知道如何解决它。

I doubt that this has anything to do with async really. 我怀疑这是否与异步有关。 Currently you're copying one stream into a MemoryStream , but then leaving the "cursor" at the end of the MemoryStream ... anything trying to read from it won't see the new data. 当前,您正在将一个流复制到MemoryStream ,但随后将“游标”保留在MemoryStream的末尾...尝试从中读取的任何内容都不会看到新数据。

The fix is really simple: just "rewind" the stream before you call your saveBlob method: 修复非常简单:在调用saveBlob方法之前,只需“倒带”流:

using (var stream = manager.GetStream())
{
   await itemFileUpload.MktRpt.CopyToAsync(stream);
   stream.Position = 0;
   await _azureStorageService.saveBlob(stream, Path.GetFileName(itemFileUpload.MktRpt.FileName));
}

Alternatively, avoid the copying into the MemoryStream entirely: 另外,请避免完全复制到MemoryStream

using (var stream = itemFileUpload.MktRpt.OpenReadStream())
{
    await _azureStorageService.saveBlob(stream, Path.GetFileName(itemFileUpload.MktRpt.FileName));
}

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

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