如何将委托函数转换为内联等待

时间:2014-08-19 22:22:02

标签: c# asynchronous async-await azure-storage-blobs

我使用标准函数异步上传文件到Azure blob存储,但是我可以使用的唯一方法是使用委托将控制传递给第二个函数。但我需要第一个函数的返回值(最好使用await)。

我如何等待结果,从而返回第一个函数中的值?我可以等待委托功能吗?我想要返回blob.uri

以下是代码:

      private Uri uploadImageFileToContainer(byte[] fileContent, string containerName, string blobName)
    {
        CloudBlobClient blobClient = myAccount.CreateCloudBlobClient();
        CloudBlobContainer container = blobClient.GetContainerReference(containerName);
        container.CreateIfNotExist();
        CloudBlockBlob blockBlob = container.GetBlockBlobReference(blobName);

        // see: http://www.c-sharpcorner.com/UploadFile/40e97e/windows-azure-blockblob-putblock-method/ for details            

        HashSet<string> blocklist = new HashSet<string>();
        foreach (FileBlock block in GetFileBlocks(fileContent))
        {
            blockBlob.PutBlock(
                block.Id,
                new MemoryStream(block.Content, true),
                null
                );
            blocklist.Add(block.Id);
        }
         **AsyncCallback UploadCompleted = new AsyncCallback(OnUploadCompleted);
         blockBlob.BeginPutBlockList(blocklist, OnUploadCompleted, blockBlob);**


    }

    private void   OnUploadCompleted(IAsyncResult result)
    {
        CloudBlockBlob blob = (CloudBlockBlob)result.AsyncState;
        blob.SetMetadata();
        blob.EndPutBlockList(result );
    }

3 个答案:

答案 0 :(得分:4)

在最新版本的Azure存储客户端库中,所有API都具有相应的Async重载,该重载会返回Task。例如,请参阅CloudBlockBlob.PutBlockListAsync

答案 1 :(得分:2)

对于所有async/await方法,您需要首先制作方法async并返回Task。然后使用FromAsync将旧的异步模式包装在Task中。这样的事情应该有效。

private async Task<Uri> uploadImageFileToContainer(byte[] fileContent, string containerName, string blobName)
{ 
    ...
    await Task.Factory.FromAsync<IEnumerable<string>>(
        blockBlob.BeginPutBlockList, blockBlob.EndPutBlockList, blockList, blockBlob);
    blob.SetMetadata();
    return blob.Uri;
}

答案 2 :(得分:1)

我正在使用Windows Azure.Storage版本4.2.1

而不是:

AsyncCallback UploadCompleted = new AsyncCallback(OnUploadCompleted);
blockBlob.BeginPutBlockList(blocklist, OnUploadCompleted, blockBlob);

我可以:

await blockBlob.PutBlockListAsync(blocklist);
blockBlob.SetMetadata();
blockBlob.EndPutBlockList(result);