如何在Windows服务启动时运行任务?

时间:2013-04-12 14:12:34

标签: c# .net windows-services installutil onstart

我有一个Windows服务,我编写了代码来在OnStart()事件中运行任务:

 protected override void OnStart(string[] args)
        {
            this.DoTask();
        }

private void DoTask()
        {
            Task task1 = Task.Factory.StartNew(() => this.OriginalFileProcessor.StartPolling());

            try
            {
                Task.Wait(task1);
            }
            catch (Exception ex)
            {
                this.Log.Error("Failed running the task", ex);
            }           
        }

DoTask是一个永无止境的循环。它仅在服务停止时停止。

但是当我尝试启动服务时,它会等待很长时间然后给我以下错误:

Windows could not start the ... service on Local Computer.
Error 1053: The service did not respond to the start or control request in a timely fashion.

如何解决?

3 个答案:

答案 0 :(得分:7)

你为什么要等完你的任务?

我认为Task.Wait阻止了您当前的线程,然后您在启动服务时出现超时。

编辑:您需要删除此块:

try
{
    Task.Wait(task1);
}
catch (Exception ex)
{
    this.Log.Error("Failed running the task", ex);
}  

Task.Wait确实阻止了您当前的线程。根据{{​​3}}:

  

Task.Wait方法

     

等待任务完成执行。

编辑2 改为执行此操作

Task task1 = Task.Factory.StartNew(() => this.OriginalFileProcessor.StartPolling()).ContinueWith( t =>
{
     var aggException = t.Exception.Flatten();
     foreach(var ex in aggException.InnerExceptions)
         this.Log.Error("Failed running the task", ex);
}, 
TaskContinuationOptions.OnlyOnFaulted);

答案 1 :(得分:2)

我想这是因为你正在等待OriginalFileProcessor.StartPolling()结束,但这种情况从未发生过。您应该将任务实例移动到单独的成员中,而不是等待它完成:

private Task m_task = null;

private void DoTask()
{
    try
    {
        m_task = Task.Factory.StartNew(() => this.StartPolling());
    }
    catch
    {
        this.Log.Error("Unable to start task", ex);
        throw;  // Rethrow, so that the OS knows, there was something wrong.
    }           
}

private void StartPolling()
{
    try
    {
        this.OriginalFileProcessor.StartPolling();
    }
    catch (Exception ex)
    {
        this.Log.Error("Failed running the task", ex);
    }
}

答案 2 :(得分:1)

在循环中,您需要检查服务状态是否“停止”并退出循环。在操作系统决定杀死你之前你有5秒钟的时间。

相关问题