I'm trying to build a simple alarm clock application that shows a MessageBox at a particular time. I've been trying to teach myself about threading, but I'm having a hard time putting my finger on what I need (since there's so many different ways to do everything, it seems). There are a ton of tutorials out there, but I haven't stumbled upon any good ones. I understand the basics of running threads, but I don't understand how to do inter-thread communication (with everything running asynchronously)
Right now, I have a while loop that checks to see if the system time matches the alarm time.
Obviously, it runs the CPU at 100% all the time. So I tried putting Thread.Sleep() in the loop, but obviously, that just locks up the UI. If I start the while loop on its own thread, it can't access the alarm control's value (or at least, I can't figure out a way to get it to do so). If I were to pass that information to the thread in some way, how could I update the thread if the alarm control changes? I'm currently using the TimePicker from the Avalon control library, which has generous amounts of properties and event handlers. Could someone help me understand how to use threading in this case? Or is there a much simpler way of doing this?
If you pass a reference to your main UI class to the worker thread when you start it up, you have a way to refer back to the controls in the UI.
this.queueServ = new QueueServicer(this);
this.queueServiceThrd = new Thread(new ThreadStart(this.queueServ.ServiceQueue));
QueueServicer is the class that I wrote to implement the worker thread in this example (the particular code I took the example from deals with servicing a queue maintained by the main thread). One of the things it contains is a method called ServiceQueue which is the actual thread proc for the worker thread. As you can see, an instance of the UI class is passed in the constructor for the worker thread class. This allows the worker thread to get access back to the main UI.
You cannot simply update the UI controls using the passed in class reference. You have to use the methods described in the article above to avoid cross-threading problems.