除了使用线程之外,监视 C# 中的控件
我有一个 winform 应用程序,其中有很多需要持续监控的控件。例如,有一个按钮,只有当其他两个按钮被禁用时才应启用它,并且它们在不同的实例中禁用。所以我现在正在做的是使用一个线程来监视连续 while 循环中的其他两个按钮,尽管
while(true)
{
if(btn.enabled==false and btn1.enabled==false)
{
bt3.enabled==true
}
}
它执行了我需要的操作,但对我来说似乎是错误的。另外,考虑到我必须生成来管理控件的线程数量,它的成本非常高,某些控件需要检查五到六个不同的事情才能执行操作,而线程对我来说似乎是唯一可能的方法。
请告诉我是否还有其他方法可以做到这一点
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这不仅效率低下,而且是错误的。由于线程关联性,除了 UI 线程之外,您不应该访问控件的属性。 设置属性(启用的分配)特别糟糕,但读取它们(启用的检查)就足够糟糕了。
这些表单应该根据事件通知自行更新,而不是持续监控。例如,通过挂钩
EnabledChanged
。
您也可以(相反)在导致
Enabled
属性发生更改的代码中执行此操作。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.you could also (instead) do this at the code that causes the
Enabled
property to change.