我正在C#中创建一个从Amazon AWS S3存储下载文件的下载应用程序。我可以毫无问题地下载文件,但我正在尝试创建一个进度事件。
要创建事件,我在下载功能中使用以下代码:
Application.DoEvents();
response2.WriteObjectProgressEvent += displayProgress;
Application.DoEvents();
我创建的事件处理程序如下:
private void displayProgress(object sender, WriteObjectProgressArgs args)
{
// Counter for Event runs
label7.BeginInvoke(new Action(() => label7.Text = (Convert.ToInt32(label7.Text)+1).ToString()));
Application.DoEvents();
// transferred bytes
label4.BeginInvoke(new Action(() => label4.Text = args.TransferredBytes.ToString()));
Application.DoEvents();
// progress bar
progressBar1.BeginInvoke(new Action(() => progressBar1.Value = args.PercentDone));
Application.DoEvents();
}
问题是它只在下载文件时更新,但事件运行得更频繁。当我下载最后一个文件(12MB); lable7(事件计数器)从3跳到121,所以我知道它正在运行,但只是没有更新。
我也尝试了一个标准'调用,但我得到了相同的结果。
该功能的附加代码:
AmazonS3Config S3Config = new AmazonS3Config
{
ServiceURL = "https://s3.amazonaws.com"
};
var s3Client = new AmazonS3Client(stuff, stuff, S3Config);
ListBucketsResponse response = s3Client.ListBuckets();
GetObjectRequest request = new GetObjectRequest();
request.BucketName = "dr-test";
request.Key = locationoffile[currentdownload];
GetObjectResponse response2 = s3Client.GetObject(request);
response2.WriteObjectProgressEvent += displayProgress;
string pathlocation = Path.GetDirectoryName(Directory.GetCurrentDirectory()) + "\\" + Instrument[currentdownload] + "\\" + NewFileName[currentdownload];
response2.WriteResponseStreamToFile(pathlocation);
答案 0 :(得分:0)
您没有使用GetObject
或WriteResponseStreamToFile
的异步调用,因此UI线程(您正在调用它)将被阻止,这意味着它无法更新进度(无论那些DoEvents
通话被认为是邪恶的,你应该避免)。
如果没有真正自己尝试,我认为你需要这样做。
private async void Button_Click(object sender, EventArgs e)
{
foreach(...download....in files to download){
AmazonS3Config S3Config = new AmazonS3Config
{
ServiceURL = "https://s3.amazonaws.com"
};
var s3Client = new AmazonS3Client(stuff, stuff, S3Config);
ListBucketsResponse response = s3Client.ListBuckets();
GetObjectRequest request = new GetObjectRequest();
request.BucketName = "dr-test";
request.Key = locationoffile[currentdownload];
GetObjectResponse response2 = await s3Client.GetObjectAsync(request, null);
response2.WriteObjectProgressEvent += displayProgress;
string pathlocation = Path.GetDirectoryName(Directory.GetCurrentDirectory()) + "\\" + Instrument[currentdownload] + "\\" + NewFileName[currentdownload];
await response2.WriteResponseStreamToFileAsync(pathlocation, null);
}
}
我添加的两个null
用于取消令牌,我无法告知AWS文档是否允许传递空令牌,如果不是,请创建一个并传递它在。