Chain ContinueWith任务

时间:2017-08-24 16:14:00

标签: c# asp.net asp.net-core async-await task

我有以下两个任务的示例。当第一个完成时,第二个应该使用第一个结果。我是这个领域的新手我如果有人指导我如何链接它,我将不胜感激:

    public async Task<string> UploadFile(string containerName, IFormFile file)
    {
        //string blobPath = "";
        var container = GetContainer(containerName);
        var fileName = file.FileName;
        CloudBlockBlob blob = container.GetBlockBlobReference(fileName);
        using (var memoryStream = new MemoryStream())
        {
            // await file.CopyToAsync(memoryStream);
            // await blob.UploadFromStreamAsync(memoryStream);

            // upload only when the 'memoryStream' is ready 
            Task.Factory.StartNew(() => file.CopyToAsync(memoryStream))
                .ContinueWith(m => blob.UploadFromStreamAsync(m.Result)); // ??
        }
        return blob.Uri.AbsoluteUri;
    }

如果不是第二种变体:

public string UploadFile(string containerName, IFormFile file)
{
    var container = GetContainer(containerName);
    var fileName = file.FileName;
    CloudBlockBlob blob = container.GetBlockBlobReference(fileName);
    using (var memoryStream = new MemoryStream())
    {
        file.CopyToAsync(memoryStream).Wait();
        blob.UploadFromStreamAsync(memoryStream).Wait();

        //Task.Factory.StartNew(() => file.CopyToAsync(memoryStream))
        //    .ContinueWith(m => blob.UploadFromStreamAsync(m.Result)); // ??
    }
    return blob.Uri.AbsoluteUri;
}

1 个答案:

答案 0 :(得分:3)

IFormFile获取流并直接上传

public async Task<string> UploadFile(string containerName, IFormFile file)
{
    //string blobPath = "";
    var container = GetContainer(containerName);
    var fileName = file.FileName;
    CloudBlockBlob blob = container.GetBlockBlobReference(fileName);
    await blob.UploadFromStreamAsync(file.OpenReadStream())
    return blob.Uri.AbsoluteUri;
}