Safely Update .Net Winform from Threads or Timer Ticks
Update The following article is one way to to achieve threading…But an easier way to try first is the BackGround Worker component (How to: Run an Operation in the Background). The below article shows how to invoke back to the form which is a step one does not have to do directly with the background worker due to its design.
// This is the format the delegate method
// will use when invoking back to the main gui
// thread.
public delegate void DataAcquired( object sender );
// The main thread will check for events
// invoked by subscribed threads here.
// This is the subscription point for the
// threads.
public event DataAcquired OnDataAcquiredEvent;
In the above example we are just using an object to pass between the threads, but you can specify anything you want which is dictated by your circumstances.
Step 2 then have the form subscribe to the event (as in the constructor) which will be eventually be consumed by the worker threads or timers.
OnDataAcquiredEvent +=
new DataAcquired(ThreadReportsDataAquiredEvent);
Note intellisense will do the above steps for you after the +=, accept them and it will do the next step
Step 3 Create the method that will handle the GUI update event
private void ThreadReportsDataAquiredEvent( object sender )
{
tsslStatus.Text = sender.ToString();
}
- Line 01: The thread/timer passes in an object which we will use to update the screen.
- Line 03: We will take the object’s information from its ToString() and place it on a label on the form for the end user to see.
Step 4: In the timer tic method or the worker thread method we will call this method which will invoke back to the main thread:
private void PushStatus(string status)
{
this.Invoke(this.OnDataAcquiredEvent,
new object[] { status });
}
Note: One doesn’t have to create a separate method; the invoke line is all one has to do. We create the event and fire it to the GUI thread.
That is a safe way to update the screen for worker threads or timer tick events.