我按照 回答 来实现我的异步showdialog。
在 LoadDataAsync()
我想显示一个MessageBox让用户选择是或不是继续或不继续。但是MessageBox没有显示。试了一会儿,我加了这行。await Task.Delay(1);
在 MessageBox.Show();
. 消息框可以正常显示。
我的问题是
await Task.Delay(1);
之前 MessageBox.Show();
. 消息框可以正常显示。是否正确?还是只是在某些情况下能正常工作?progressForm
是否完全显示?progressForm
完全显示,然后再显示MessageBox?下面是我的代码。
using System;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApp
{
public partial class MainForm : Form
{
Form progressForm;
public MainForm()
{
InitializeComponent();
}
async Task<int> LoadDataAsync()
{
await Task.Delay(1); //why add this line, the MessageBox can show normally?
var result = MessageBox.Show("Do you want to continue?", "Question", MessageBoxButtons.YesNo);
if (result == DialogResult.Yes)
{
await Task.Delay(2000);
}
else
{
return -1;
}
await Task.Delay(2000);
return 42;
}
private async void button1_Click(object sender, EventArgs e)
{
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();
}
}
}
这是正确的方法还是有更好的方法?
谢谢你的帮助。