该
onStart()回调需要及时归还,所以你要揭开序幕,所有的工作都将执行一个线程。我建议向您的班级添加以下字段:
using System.Threading;private ManualResetEvent _shutdownEvent = new ManualResetEvent(false);private Thread _thread;
该
_thread字段将包含对
System.Threading.Thread您在
onStart()回调中创建的对象的引用。该
_shutdownEvent字段包含系统级事件构造,该构造将用于向线程发出信号,以在服务关闭时停止运行。
在
onStart()回调中,创建并启动线程。
protected override void onStart(string[] args){ _thread = new Thread(WorkerThreadFunc); _thread.Name = "My Worker Thread"; _thread.IsBackground = true; _thread.Start();}您需要一个命名函数
WorkerThreadFunc才能使其正常工作。它必须匹配
System.Threading.ThreadStart委托人签名。
private void WorkerThreadFunc(){}如果您在此函数中未添加任何内容,线程将启动,然后立即关闭,因此您必须在其中放置一些逻辑,这些逻辑基本上可以在工作时使线程保持活动状态。这是
_shutdownEvent派上用场的地方。
private void WorkerThreadFunc(){ while (!_shutdownEvent.WaitOne(0)) { // Replace the Sleep() call with the work you need to do Thread.Sleep(1000); }}while循环检查,
ManualResetEvent以查看是否已“设置”。由于我们使用初始化了对象
false,因此此检查返回false。在循环内部,我们睡眠1秒钟。您需要将其替换为所需的工作-
监视代理设置等。
最后,在
onStop()Windows服务的回调中,您要向线程发出停止运行的信号。使用,这很容易
_shutdownEvent。
protected override void onStop(){ _shutdownEvent.Set(); if (!_thread.Join(3000)) { // give the thread 3 seconds to stop _thread.Abort(); }}希望这可以帮助。



