Reputation: 1856
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.
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.
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
}
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.
VS2008, .net 3.5
Upvotes: 0
Views: 2182
Reputation: 43626
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; });
}
Upvotes: 2