在不"锁定"UI的情况下执行简单逻辑

Luk*_*rig 0 c# winforms

我有一个带有一些txb和一个按钮的对话框.单击此按钮时,我想更改按钮的文本,禁用按钮,启动一些逻辑,然后关闭窗口.

该逻辑没有返回,它只是设置一个静态变量.但它可能需要一分钟,因为它连接到数据库.

如何从Freezing中停止WinFroms UI?我正在寻找一种简单的方法,如果可能的话,没有新的类和文件.

And*_*tar 5

这就是我要做的事情:

private async void ButtonClick() 
{
    //here, you're on the UI Thread
    button1.Enabled = false;

    await Task.Run(() => DoTheWork());

    //you're back on the UI Thread
    button1.Enabled = true;
}

private void DoTheWork() 
{
    //this will be executed on a different Thread
}
Run Code Online (Sandbox Code Playgroud)