简体   繁体   English

在c#中监视控件,而不是使用线程

[英]monitoring a control in c# other than using threads

i have a winform application in which i have a lot of controls that needs continuos monitoring. 我有一个Winform应用程序,其中有很多需要持续监控的控件。 For example there is a button and it should be enabled only when two other buttons are disabled, and they disable at separate instances. 例如,有一个按钮,仅当其他两个按钮被禁用并且在单独的实例中被禁用时,才应启用它。 So what i am doing now is using a thread to monitor the two other buttons in a continuos while loop such as 所以我现在正在做的是使用一个线程来监视一个连续的while循环中的另外两个按钮,例如

while(true)
{    
if(btn.enabled==false and btn1.enabled==false)
{
bt3.enabled==true
}
}

though it does what i need it seems wrong to me. 尽管它满足了我的需求,但对我来说似乎是错的。 Also its very expensive considering the number of threads i have to spawn to manage my controls, there are certain controls that needs to check five or six different things to before it can do an action and threading seems the only way possible to me. 考虑到我必须产生的线程数来管理控件,这也是非常昂贵的,某些控件在执行操作之前需要检查五到六种不同的东西,而线程对我来说似乎是唯一的方法。

Please tell me if there is any other way to do this 请告诉我是否还有其他方法可以做到这一点

Not only is that inefficient, it is incorrect; 那不仅效率低下,而且是不正确的。 you should never access a control's properties except from the UI thread, due to thread affinity. 由于线程的相似性,您永远不要从UI线程访问控件的属性。 Setting properties (the enabled assignment) is especially bad, but reading them (the enabled check) is bad enough. 设置属性(已启用的分配)特别糟糕,但是读取属性(已启用的检查)已经很糟糕。

Rather than continuous monitoring, those forms should update themselves , based on event notifications. 这些表单应该基于事件通知来更新自身 ,而不是进行持续监视。 For example, by hooking EnabledChanged on the two buttons. 例如,通过钩上两个按钮上的EnabledChanged

// (in the form initialization code)
btn.EnabledChanged += UpdateButtons;
btn1.EnabledChanged += UpdateButtons;

//...
private void UpdateButtons(object sender, EventArgs args)
{
     bt3.Enabled = !btn.Enabled && !btn1.Enabled;
}

you could also (instead) do this at the code that causes the Enabled property to change. 您也可以(而不是)在导致Enabled属性更改的代码上执行此操作。

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

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