简体   繁体   English

使用BeginInvoke禁用表单控件

[英]Using BeginInvoke to disable form controls

I'm using the following code to disable form controls while i'm doing some longTask() thread. 在执行一些longTask()线程时,我使用以下代码禁用表单控件。 But the controls are not getting disabled.. Here is my code for disable() method. 但是控件没有被禁用。这是我的disable()方法的代码。

    public void disableFormControls()
    {
        if (InvokeRequired)
        {
            this.BeginInvoke(new Action(disableFormControls));
            return;
        }
        groupBoxInput.Enabled = false;
        groupBoxOutput.Enabled = false;
        btnGen.Enabled = false;
        btnReset.Enabled = false;
    }

Here is how i'm calling it.. NOTE: LongTask() will be running in a separate thread. 这是我的调用方式。注意:LongTask()将在单独的线程中运行。

    private void LongTask()
    {
        disableFormControls();
        Console.WriteLine("Started Records::" + DateTime.Now);
        //Doing my long tasks here 
        enableFormControls();
    }

Can you please let me know where i'm wrong.. 你能告诉我我哪里错了..

Try this, I changed the Invoke of enableForm to instead call disableFormControls . 试试这个,我改变了调用enableForm改为调用disableFormControls Also I did this synchronously instead of asynchronously so your background thread isn't doing anything until the UI is updated properly. 另外,我是同步而不是异步执行此操作的,因此您的后台线程在UI正确更新之前不会做任何事情。 I'm also assuming disableFormControls is a method on your Form. 我还假设disableFormControls是您Form上的一个方法。

public void disableFormControls()
{
    if (InvokeRequired)
    {
        this.Invoke(new Action(disableFormControls));
        return;
    }
    groupBoxInput.Enabled = false;
    groupBoxOutput.Enabled = false;
    btnGen.Enabled = false;
    btnReset.Enabled = false;
}

为确保在UI线程上同步执行代码,请使用Invoke而不是BeginInvoke

You have two choices here as you can cannot modify winform UI controls from non UI thread 您在这里有两个选择,因为您无法从非UI线程修改winform UI控件

  1. You can move the enable/disable UI code back to the UI thread. 您可以将启用/禁用UI代码移回UI线程。 Before starting the task disable the controls in the UI thread and use the dispatcher to enable them back in the UI thread at task completion. 在开始任务之前,请禁用UI线程中的控件,并使用分派器在任务完成时将其重新启用到UI线程中。

  2. You can use data binding to bind the enable state of these controls to some no UI object that you can freely modify from any thread. 您可以使用数据绑定将这些控件的启用状态绑定到可以从任何线程自由修改的某些UI对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM