使用Progress Bar WPF进行异步Google文件上传

kem*_*yyy 5 .net c# wpf google-cloud-storage progress-bar

我使用服务帐户上传到Google云端存储.我需要能够在WPF UI中显示上传的进度.现在,每当我尝试更新ProgressBar.Value时,它都不起作用,但是当我在控制台中编写bytesSent时,我可以看到进度.

    public async Task<bool> UploadToGoogleCloudStorage(string bucketName, string token, string filePath, string contentType)
    {
        var newObject = new Google.Apis.Storage.v1.Data.Object()
        {
            Bucket = bucketName,
            Name = System.IO.Path.GetFileNameWithoutExtension(filePath)
        };
        var service = new Google.Apis.Storage.v1.StorageService();

        try
        {
            using (var fileStream = new FileStream(filePath, FileMode.Open))
            {

                var uploadRequest = new ObjectsResource.InsertMediaUpload(service, newObject, bucketName, fileStream, contentType);
                uploadRequest.OauthToken = token;
                ProgressBar.Maximum = fileStream.Length;
                uploadRequest.ProgressChanged += UploadProgress;
                uploadRequest.ChunkSize = (256 * 1024);
                await uploadRequest.UploadAsync().ConfigureAwait(false);
                service.Dispose();

            }

        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
            throw ex;
        }
        return true;
    }

    private void UploadProgress(IUploadProgress progress)
    {
        switch (progress.Status)
        {
            case UploadStatus.Starting:
                ProgressBar.Minimum = 0;
                ProgressBar.Value = 0;

                break;
            case UploadStatus.Completed:
                System.Windows.MessageBox.Show("Upload completed!");
                break;
            case UploadStatus.Uploading:
                //Console.WriteLine(progress.BytesSent); -> This is working if I don't call the method below.
                UpdateProgressBar(progress.BytesSent);
                break;
            case UploadStatus.Failed:
                Console.WriteLine("Upload failed "
                            + Environment.NewLine
                            + progress.Exception.Message
                            + Environment.NewLine
                            + progress.Exception.StackTrace
                            + Environment.NewLine
                            + progress.Exception.Source
                            + Environment.NewLine
                            + progress.Exception.InnerException
                            + Environment.NewLine
                            + "HR-Result" + progress.Exception.HResult);
                break;
        }
    }

    private void UpdateProgressBar(long value)
    {
        Dispatcher.Invoke(() => { this.ProgressBar.Value = value; });
    }
Run Code Online (Sandbox Code Playgroud)