异步的ShowDialog [英] Async ShowDialog
问题描述
我使用异步/伺机异步从数据库,并在加载过程中加载我的数据,我想弹出一个装载形式,它只是一个简单的形式与运行进度条,表明有一个正在运行的进程。数据被加载后,对话框会自动关闭。我怎样才能做到这一点?下面是我目前的code:
I'm using async/await to asynchronously load my data from database and during the loading process, I want to popup a loading form, it's just a simple form with running progress bar to indicate that there's a running process. After data has been loaded, the dialog will automatically be closed. How can I achieve that ? Below is my current code:
protected async void LoadData()
{
ProgressForm _progress = new ProgressForm();
_progress.ShowDialog() // not working
var data = await GetData();
_progress.Close();
}
更新:
我设法得到它的工作通过改变code:
I managed to get it working by changing the code:
protected async void LoadData()
{
ProgressForm _progress = new ProgressForm();
_progress.BeginInvoke(new System.Action(()=>_progress.ShowDialog()));
var data = await GetData();
_progress.Close();
}
这是正确的做法或有任何更好的方法?
Is this the correct way or there's any better ways ?
感谢您的帮助。
推荐答案
这很容易与 Task.Yield
来实现,就像这样(的WinForms,没有异常处理简单)
It's easy to implement with Task.Yield
, like this (WinForms, no exception handling for simplicity):
namespace WinFormsApp
{
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
}
async Task<int> LoadDataAsync()
{
await Task.Delay(2000);
return 42;
}
private async void button1_Click(object sender, EventArgs e)
{
var progressForm = new Form() {
Width = 300, Height = 100, Text = "Please wait... " };
var progressFormTask = progressForm.ShowDialogAsync();
var data = await LoadDataAsync();
progressForm.Close();
await progressFormTask;
MessageBox.Show(data.ToString());
}
}
internal static class DialogExt
{
public static async Task<DialogResult> ShowDialogAsync(this Form @this)
{
await Task.Yield();
if (@this.IsDisposed)
return DialogResult.OK;
return @this.ShowDialog();
}
}
}
要了解这里的执行流程如何跳转到一个新的嵌套的消息循环(即模态对话框),然后又回到了原来的消息循环(这就是等待progressFormTask $是很重要的C $ C>是)。
It's important to understand here how the execution flow jumps over to a new nested message loop (that of the modal dialog) and then goes back to the original message loop (that's what await progressFormTask
is for).
这篇关于异步的ShowDialog的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!