读书人

stop windows service 时怎么等当前循

发布时间: 2012-09-15 19:09:29 作者: rapoo

stop windows service 时如何等当前循环结束在结束
private ManualResetEvent _shutdownEvent = new ManualResetEvent(false);
private Thread _thread;

protected override void OnStart(string[] args)
{
_thread = new Thread(WorkerThreadFunc);
_thread.Name = "Upload";
_thread.IsBackground = true;
_thread.Start();
}

protected override void OnStop()
{
_shutdownEvent.Set();
if (!_thread.Join(3000))// give the thread 3 seconds to stop
{
_thread.Abort();
}
}

protected void WorkerThreadFunc()
{
while (!_shutdownEvent.WaitOne(1000))
{
DoWork();
}
}

DoWork 是反复扫描一个目录,如果发现有订单数据(其他程序放进去的),就upload到ftp上,当stop这个service时,我想等dowork()结束,在终止service.否则会发生一个订单数据(若干文件组成)一部分传到ftp,一部分还在本地的情况。

[解决办法]
_thread = new Thread(WorkerThreadFunc);
这句使用using应该可以吧.

C# code
protected override void OnStart(string[] args){  using(_thread = new Thread(WorkerThreadFunc))  {    _thread.Name = "Upload";    _thread.IsBackground = true;    _thread.Start();  }}
[解决办法]
你的代码没有问题啊。如果DoWork比较长得话,给Join长点得时间

!_thread.Join(60000) --一分钟。
_thread.Join() --一直等待

读书人网 >C#

热点推荐