在wpf中利用异步lambda编程,模拟数据库连接,防止界面假死
作者:互联网
参考《图解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;
}
}
标签:false,SetGuiValues,数据库,假死,isConnected,private,wpf,true,lambda 来源: https://www.cnblogs.com/AlexanderZhao/p/12190236.html