C# Windows 服务:OnStart 循环 - 我需要委托吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/649935/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 11:46:37  来源:igfitidea点击:

Windows Services: OnStart loop - do I need to delegate?

c#.netwindows-services

提问by Rob Stevenson-Leggett

I've got a windows service which scans a folder every n seconds for changes. I'm getting "the service did not respond to the start command in a timely fashion" when trying to start it up.

我有一个 Windows 服务,它每 n 秒扫描一个文件夹以进行更改。尝试启动时,我收到“服务没有及时响应启动命令”的消息。

I've got a loop setting off in OnStart like so:

我在 OnStart 中设置了一个循环,如下所示:

 public void OnStart(string[] args)
 {
    while (!_shouldExit)
    {
        //Do Stuff

        //Repeat
        Thread.Sleep(_scanIntervalMillis);
    }
 }

Is this what is causing the error? Should I delegate this method?

这是导致错误的原因吗?我应该委托这个方法吗?

采纳答案by Marc Gravell

OnStart should only startthe work; it isn't responsible for doing it. This typically means spawning a new thread to do the actual work. It is expected that OnStart completes promptly. For example:

OnStart 应该只开始工作;它不负责这样做。这通常意味着产生一个新线程来完成实际工作。预计 OnStart 会迅速完成。例如:

    public void OnStart(string[] args) // should this be override?
    {
        var worker = new Thread(DoWork);
        worker.Name = "MyWorker";
        worker.IsBackground = false;
        worker.Start();
    }
    void DoWork()
    {
        // do long-running stuff
    }

回答by Darin Dimitrov

The OnStart method shouldn't block. You need to spawn a worker thread that will do the job. You could also take a look at the FileSystemWatcherclass to scan for file system change notifications.

OnStart 方法不应阻塞。您需要生成一个工作线程来完成这项工作。您还可以查看FileSystemWatcher类以扫描文件系统更改通知。