i have a winform application in which i have a lot of controls that needs continuos monitoring. 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(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. 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.
// (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.
精彩评论