我有一个上传图片的小服务,我就这样使用它:
ImageInfo result = await service.UploadAsync(imagePath);
我想要做的是显示进度对话框,但前提是上传操作需要的时间超过2秒。上传完成后,我想关闭进度对话框。
我使用Task / ContinueWith做了一个粗略的解决方案,但我希望有一种更“优雅”的方式。
如何使用async/await
实现此目的?
答案 0 :(得分:3)
可能是这样的吗?
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();
}
答案 1 :(得分:3)
我以为我仍然会发布我的解决方案,因为它说明了如何显示和关闭模态对话框。它适用于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<bool>();
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
}
}