无需“锁定"即可执行简单逻辑用户界面 [英] Execute simple Logic without "locking" the UI

查看:27
本文介绍了无需“锁定"即可执行简单逻辑用户界面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a dialog with some txb's and a button. When this button is clicked I want to change the button's Text, disable the button, start some Logic and then close the Window.

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

That logic has no return, it just sets a static variable. But it can take a minute because it connects to a DB.

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

How can I stop the WinFroms UI from Freezing? I'm looking for a simple approach, if possible no new Classes and Files.

推荐答案

我会这样做:

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
}

这篇关于无需“锁定"即可执行简单逻辑用户界面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆