仅当任务未在指定时间内完成时才显示进度对话框

我有一个上传图像的servlets,我这样使用它:

ImageInfo result = await service.UploadAsync(imagePath); 

我想要做的是显示进度对话框,但前提是上传操作需要超过2秒。 上传完成后,我想关闭进度对话框。

我使用Task / ContinueWith做了一个粗略的解决方案,但我希望有一种更“优雅”的方式。

如何使用async/await实现此目的?

可能是这样的?

 var uploadTask = service.UploadAsync(imagePath); var delayTask = Task.Delay(1000);//Your delay here if (await Task.WhenAny(new[] { uploadTask, delayTask }) == delayTask) { //Timed out ShowProgress ShowMyProgress(); await uploadTask;//Wait until upload completes //Hide progress HideProgress(); } 

我以为我仍然会发布我的解决方案,因为它说明了如何显示和解除模态对话框。 它适用于WPF,但同样的概念适用于WinForms。

 private async void OpenCommand_Executed(object sCommand, ExecutedRoutedEventArgs eCommand) { // start the worker task var workerTask = Task.Run(() => { // the work takes at least 5s Thread.Sleep(5000); }); // start timer task var timerTask = Task.Delay(2000); var task = await Task.WhenAny(workerTask, timerTask); if (task == timerTask) { // create the dialog var dialogWindow = CreateDialog(); // go modal var modalityTcs = new TaskCompletionSource(); dialogWindow.Loaded += (s, e) => modalityTcs.SetResult(true); var dialogTask = Dispatcher.InvokeAsync(() => dialogWindow.ShowDialog()); await modalityTcs.Task; // we are now on the modal dialog Dispatcher frame // the main window UI has been disabled // now await the worker task await workerTask; // worker task completed, close the dialog dialogWindow.Close(); await dialogTask; // we're back to the main Dispatcher frame of the UI thread } }