I'm currently trying to get into multithreading to take care of my recurring tasks.
In some cases I need to perform tasks recurring for the entire duration of which the application is running.
One simple example is to display the current time.
I could just use a simple timer but that's probably not best practice. So I understand that I need to use a separate thread to do this. And since I need this clock to be pretty accurate I probably should assign a single thread to this one process in stead of using the thread pool and I would need to use it asynchronously so that the UI is not waiting for the separate thread to finish.
So I'm thinking of creating a process where I get the time from the pc and I extract the hours, minutes and seconds from it. Then I put in a thread.sleep for 100 ms and execute it again. In order for me to control the execution I'm also thinking of putting in a start and a stop-method.
Starting would be pretty straightforward, when you invoke the thread, that's your start but the problem is how to stop it?
I know I probably should be using the BeginInvoke, EndInvoke and IAsyncResult to achieve all this but I'm not sure how to get the pieces working together.
Expand|Select|Wrap|Line Numbers
- while(clockActivated)
- {
- string currentTime;
- currentTime = DateTime.Now.ToString("HH:mm:ss tt");
- lblClock.Text = currentTime;
- Thread.Sleep(10);
- }
- How can I start a thread which runs continuously?
- How can I pass the result back to a label on my form?
- How can I stop the thread which is in a continuous loop?
I hope some here can help me.
Thanks,
Kenneth