参考《图解C#》第20章异步编程第五节程序,解决在wpf中连接数据库,界面假死问题。
public partial class MainWindow : Window
{
private bool isConnected = false;
public MainWindow()
{
InitializeComponent();
startWorkButton.Click += async (sender, e) =>
{
SetGuiValues(false, "正在连接数据库");
await DoSomeWork();
if (isConnected==true)
{
SetGuiValues(true, "数据库连接成功");
}
else
{
SetGuiValues(true, "数据库连接失败");
}
};
}
/// <summary>
/// 模拟连接数据库
/// </summary>
/// <returns></returns>
private Task DoSomeWork()
{
Random random = new Random();
int rndValue = random.Next(0, 10);
if (rndValue%3==0)
{
isConnected = true;
}
else
{
isConnected = false;
}
return Task.Delay(2500);
}
private void SetGuiValues(bool buttonEnabled, string status)
{
startWorkButton.IsEnabled = buttonEnabled;
workStartedTextBlock.Text = status;
}
}