1

我正在用 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);
4

1 回答 1

0

您没有使用GetObjector的异步调用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);

  }
 }

我添加的两个nulls 用于取消令牌,我无法从 AWS 文档中判断是否允许传递空令牌,如果不允许,请创建一个并传递它。

于 2018-05-31T23:11:08.087 回答