简体   繁体   中英

How to change a GUI control state by the event handler

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

You will have to invoke it back onto the UI thread

private void GetDataFailedEventHander_EnableButtonState(object s, EventArgs e)
{
    base.Invoke((Action)delegate { btnGet.Enabled = true; }); 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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