使用任务库进行Amazon S3异步上传

时间:2013-09-14 22:51:36

标签: c# amazon-s3 task-parallel-library async-await

我有一个将文件上传到Amazon S3的Windows窗体。我试图实现内置的异步方法,但似乎没有正常工作,所以我认为最好的方法是实现System.Threading.Tasks。

我的实际代码如下:

public void UploadFileAsync(string bucketName, CloudDocument doc, bool publicRead)
{
config = new AmazonS3Config();
            config.CommunicationProtocol = Protocol.HTTP;
            client = Amazon.AWSClientFactory.CreateAmazonS3Client(accessKeyID, secretAccessKeyID, config);

// Load stream from file location
            FileMode mode = FileMode.Open;
            using (FileStream fs = new FileStream(doc.FullName, mode, FileAccess.Read))
            {
                // Create put object request
                TransferUtilityUploadRequest objectRequest = new TransferUtilityUploadRequest();
                objectRequest.InputStream = fs;
                objectRequest.BucketName = bucketName;

                if (publicRead) objectRequest.CannedACL = S3CannedACL.PublicRead;

                objectRequest.Key = doc.KeyName + doc.FileName.Replace(' ', '_');

                objectRequest.UploadProgressEvent += new EventHandler<UploadProgressArgs>(UploadProgressEvent);

                transferUtility = new TransferUtility(client);
                IAsyncResult asyncResult = transferUtility.BeginUpload(objectRequest, new AsyncCallback(UploadCallBack), results);

                waitHandles.Add(asyncResult.AsyncWaitHandle);



                // Wait till all the requests that were started are completed.
                WaitHandle.WaitAll(waitHandles.ToArray());
            }

            client.Dispose();

        }

}
private void UploadProgressEvent(object sender, UploadProgressArgs e)
        {
            if (UploadProgressChanged != null)
                UploadProgressChanged(this, e);
        }

private void UploadCallBack(IAsyncResult result)
        {

            Results results = result.AsyncState as Results;
            try
            {

                // If there was an error during the put attributes operation it will be thrown as part of the EndPutAttributes method.
                transferUtility.EndUpload(result);

                results.Successes++;
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                results.Errors++;
            }
        }

是否有人尝试实施Await / Async Task以将异步上传到amazon s3?

2 个答案:

答案 0 :(得分:3)

您可以在MSDN上找到wrapping APM and EAP members into TAP members的说明。

总之,您使用Task.Factory.FromAsync来包装Begin / End方法对,如下所示:

public static Task UploadAsync(this TransferUtility @this, TransferUtilityUploadRequest request)
{
    return Task.Factory.FromAsync(@this.BeginUpload, @this.EndUpload, request, null);
}

然后你可以这样使用它:

var task = transferUtility.UploadAsync(objectRequest);
tasks.Add(task);
await Task.WhenAll(tasks);

答案 1 :(得分:0)

您可能也对AWS SDK 2.0 for .NET的开发者预览感兴趣。可以找到TransferUtility的异步扩展类的源here。如果您对预览有任何反馈,请告诉我们!

谢谢!