我有一个将文件上传到 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?