AWS S3 的 C# UI 未更新

C# UI for AWS S3 not updating

我正在用 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,所以我知道它是 运行,但只是没有更新。

我也试过 'standard' 调用,但结果相同。

函数的附加代码:

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);

您没有使用 GetObjectWriteResponseStreamToFile 的异步调用,因此 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 文档中判断是否允许传递空令牌,如果不允许,请创建一个并将其传入。