Request description
I'm handling a project which need to call a background process to read some data from database. The get data button of the GUI will turn to gray during this time and turn to enable after the data arrived. If there is any exception throw from the background process the button need to turn to enable to make sure the user could send another request.
Problem description
One get data failed event is added to the background process to let the UI thread notice there is a exception encountered by the get data process. But the state of the button can't be changed in the event handler function due to there are running in the difference thread.
Relative codes snippets
Back ground thread code
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(); } }
GUI codes
//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 }
Questions
How to change the UI control from the event hander in .net 3.5? In .net 4.0 may be I could use TPL to handle this. Any suggestions will be appreciated, thanks.
Development environment
VS2008, .net 3.5