System.Timers.Timer event from a completed thread
I have a C# service that I'm working on, which will load info via WMI on various servers on the network. I have set it up so that each server is represented by an instance of my ServerInfo class. In the main program, it initializes the configuration and loops through the ArrayList of servers, kicking off worker threads using ThreadPool.QueueUserWorkItem to init or update each server.
What I want to do is refresh each server in the background, after an amount of time specified in the config passes. My first thought was to set up a System.Timers.Timer object in each server instance, 开发者_Python百科and once the threaded refresh method is completed, start the timer. The main program would wait for the elapsed event, and kick off the refresh method for that server instance again.
However, it looks like once the worker thread has completed, the timer is dead in the water and never sends an elapsed event (seems kind of obvious, since the object is no longer processing anything).
What should I do to allow for triggering of updates like this?
Well, my first thought is to have the ServerInfo class handle updating internally. The ServerInfo constructor could start a timer or use QueueUserWorkItem to kick off an update thread. That way, you would not have to manage all updating logic in the main program.
The ServerInfo class could have an event that the main program subscribes to to receive updates.
It's not necessary to queue a worker thread to start a timer. Just do it in the main thread (i.e., the constructor for ServerInfo)
Of course, I'm not 100% clear on what you're trying to accomplish, so this may not fit into your situation.
System.Timers.Timer probably isn't working as you expect as it uses windows messages, so it requires a message pump, which you do not have on your threads. Instead, look into System.Threading.Timer.
But my main answer is the opposite of Chris Hogan's.. Don't do threading inside objects, but in the main application code, or at least a layer of.
So.. you create all your ServerInfo's, which at this point only contain meta data eg machine name.
Then you fire up a separate thread using System.Threading.Thread, lock the ArrayList of ServerInfo's, grab a copy of the ArrayList, then iterate through it and call an Update() method on each ServerInfo.
You can either fire an event after each Update, or after they all have updated.
Don't forget to marshal the call from the event handler of ServerInfo.Updated to the main thread! Otherwise you'll hold up the next update cycle. And it's a requirement if you are to alter UI properties.
精彩评论