The OnStart() callback should return in a timely manner, so you want to start a thread where all your work will be done. I would recommend adding the following fields to the class:
using System.Threading; private ManualResetEvent _shutdownEvent = new ManualResetEvent(false); private Thread _thread;
The _thread field will contain a reference to the System.Threading.Thread object that you create in the OnStart() callback. The _shutdownEvent field contains a system-level event construct that will be used to signal that the thread has stopped working when the service _shutdownEvent .
In the OnStart() callback, create and start your thread.
protected override void OnStart(string[] args) { _thread = new Thread(WorkerThreadFunc); _thread.Name = "My Worker Thread"; _thread.IsBackground = true; _thread.Start(); }
To do this, you need a function called WorkerThreadFunc . It must match the System.Threading.ThreadStart subscription.
private void WorkerThreadFunc() { }
If you donβt put anything into this function, the thread will start and then shut down right away, so you have to put some logic in there that basically saves the stream while you are doing your work. Here _shutdownEvent in handy.
private void WorkerThreadFunc() { while (!_shutdownEvent.WaitOne(0)) {
The while loop checks ManualResetEvent to make sure it is set or not. Since we initialized the object with false above, this check returns false. Inside the cycle, we sleep for 1 second. You will want to replace this with the work that you must do - control the proxy server settings, etc.
Finally, in the OnStop() your Windows Service, you want the thread to stop working. This is easy to use with _shutdownEvent .
protected override void OnStop() { _shutdownEvent.Set(); if (!_thread.Join(3000)) {
Hope this helps.
Matt Davis Feb 01 '11 at 17:31 2011-02-01 17:31
source share