【发布时间】:2013-01-16 08:04:16
【问题描述】:
请求说明
我正在处理一个需要调用后台进程从数据库读取一些数据的项目。 GUI 的获取数据按钮在此期间会变为灰色,并在数据到达后变为启用。如果后台进程抛出任何异常,则需要将按钮转为启用以确保用户可以发送另一个请求。
问题描述
在后台进程中添加一个获取数据失败事件,让 UI 线程通知获取数据进程遇到异常。但是由于在不同的线程中运行,因此无法在事件处理函数中更改按钮的状态。
相关代码sn-ps
-
后台线程代码
class DataProcessService { public static SingletonInstance {get;set;} //Omit the codes implement the singleton pattern public event EventHandler GetDataFailed; private void FireGetDataFailed() { if(GetDataFailed != null) GetDataFailed(this, null); } // in some function try { // do some get data process } catch(SqlException ex) { FireGetDataFailed(); } } -
图形用户界面代码
//In the init function subscribe to the event DataProcessService.SingletonInstance.GetDataFailed += new Eventhandler(GetDataFailedEventHander_EnableButtonState); private void GetDataFailedEventHander_EnableButtonState(object s, EventArgs e) { btnGet.Enabled = true; //There will be a exception }
问题
如何从 .net 3.5 中的事件处理程序更改 UI 控件?在 .net 4.0 中,我可以使用 TPL 来处理这个问题。任何建议将不胜感激,谢谢。
开发环境
VS2008,.net 3.5
【问题讨论】:
-
我认为这是 winforms?,因为大多数 winforms 开发人员甚至都不费心添加适当的标签,因为他们实际上不知道 .Net 堆栈中存在其他(更好的)UI 技术。
-
糟糕...我将添加标签 winform。谢谢。 :)
-
感谢您的链接!我发帖之前没有找到这个。
标签: c# multithreading winforms events