从不同线程启用/禁用菜单项 [英] Enabling/Disabling menu item from different thread

查看:59
本文介绍了从不同线程启用/禁用菜单项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我正在尝试从另一个线程更改菜单项.我可以在其他控件上使用InvokeRequired/Invoke,但是由于菜单项不是Control,因此很难实现相同的功能.

对于其他控件,我正在这样做:

Hi,

I am trying to change a menu item from another thread. I am able to use the InvokeRequired/Invoke on other controls, but since the menu item is not a Control, I am having difficulty in achieving the same functionality.

For other controls, I am doing this:

{
....
private delegate void SetControlEnableHandler(object sender, Boolean bValue);

private void SetControlEnabled(object sender, Boolean bValue)
        {
            Control control = (Control)sender;
            if (control.InvokeRequired)
            {
                control.Invoke(new SetControlEnableHandler(SetControlEnabled), new object[] { sender, bValue });
            }
            else
            {
                control.Enabled = bValue;
            }           
        }
....
}


从工作线程中,我简单地调用:


From the worker thread I simple call:

{
....
this.SetControlEnabled(btnPress, true);
...
}


它可以完成工作.

谁能帮我这里的菜单项?

谢谢
-Bhaskar


and it does the job.

Can anyone help me with the menu item here?

Thank You,
-Bhaskar

推荐答案

这是您需要做的:首先,使用表格中其他控件的InvokeRequiredInvoke.它将正常工作!

另外,请考虑改用BeginInvoke.如果您确定调用总是来自非UI线程,则可能要跳过InvokeRequired检查并始终使用<code> Invoke或InvokeRequired.

请在我的其他答案中查看所有详细信息: Control.Invoke()与Control .BeginInvoke() [ ^ ].

现在,我将解释为什么使用哪个控件调用调用方法都无关紧要.调用机制在Application级别和运行Application.Run的线程(通常称为UI线程)上工作.该机制在参考文档和其他参考文档中以及基于队列进行了描述. Control实例的唯一要求是使用哪个实例方法进行调用是同一Application的一部分,通常是这种情况,除非您尝试使用线程和Forms进行非常冒险的技巧.

—SA
Here is what you need to do: use InvokeRequired and Invoke of some other controls, first of all, of your form. It will work correctly!

Also, consider using BeginInvoke instead. If you''re sure that your invocation call is always from non-UI thread, you may want to skip InvokeRequired check and always use <code>Invoke or InvokeRequired.

Please see all the detail in my other Answer: Control.Invoke() vs. Control.BeginInvoke()[^].

Now, I''ll explain why it does not matter which control is used for calling the invocation methods. The invocation mechanism works at the level of Application and the thread running Application.Run usually called UI thread. The mechanism is described in the referenced document and further references and based on the queue. The only requirement for the Control instance which instance method is used for invocation is being a part of the same Application which is usually the case unless you try very risky tricks with threads and Forms.

—SA


这篇关于从不同线程启用/禁用菜单项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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