Suppose you have implemented a multi-threaded windows application, where there are dedicated threads to do certain dedicated task. Periodically during the execution of the application you want to know the status of some operation through a UI control on a form. The application which may immediately come to your mind which require this functionality might be a ‘Timer’ or ‘File download progress bar’ etc. So how do you go about implementing this functionality.
In windows application there is a dedicated thread which handle UI operations, when you create a Control for display this is the thread which is responsible for all the interaction between the applications and the controls. So if you want to the application to be responsive to the user commands, you should put as little load as possible on the UI thread, otherwise if you perform a long running task for e.g., it may take some time for the control to get back to the UI, making it appear that the application has hanged.
For illustration purpose lets a design a very simple Clock application, what it is going to do just update a text box with the time, nothing fancy. I am assuming you are familiar with Events, Delegate and Threading concepts. So over we proceed.
Create a form and put a text box control on it. Name the text box control, for e.g. “TxtBoxTimer”.
Define a method which is going to update the timer text
private void UpdateTimer(object sender, System.EventArgs e) |
Do notice the parameters for this method, they are same as “Event handler” delegate defined in .NET. we are going to call this method asynchronously.
Define a method which is going to be called by the second thread. This method wont do anything worthwhile only that it is going to call our UpdateTimer delegate defined above
|
private void UpdateTimer(object status) |
Please note the Invoke method call in the above function. The Invoke method is used to call function outside the UI thread boundaries. It is used to pass control from one thread to another. Every control has a invoke method defined. For more information on Invoke method please refer to MSDN. The Invoke method used over here is synchronous operation, if you want to use asynchronous calls call the corresponding “BeginInvoke” method.
To simulate threading, we shall use the ‘Timer’ event of the ‘Threading’ class.
Define a Timer object
|
System.Threading.Timer _timer; |
Initialize the Timer object in the Form load method
|
_timer = new System.Threading.Timer(UpdateTimer, null, 2500, 2000); |
and dont forget to free the Timer object once you are done with your work or when the form is closing.
|
_timer.Dispose(); |
Thats all you need to do, to get your own Clock application. Happy coding.
Refrences
Hottest Motorcycle Chicks
Hottest Motorcycle Chicks