加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 04:27:14 所属栏目:百科 来源:网络整理
导读:我有一个 Windows服务,我已经编写了代码来在OnStart()事件中运行任务: protected override void OnStart(string[] args) { this.DoTask(); }private void DoTask() { Task task1 = Task.Factory.StartNew(() = this.OriginalFileProcessor.StartPolling());
我有一个 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.

怎么解决?

解决方法

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

我认为Task.Wait阻止了你当前的线程,然后你在启动服务时遇到了超时.

编辑:您需要删除此块:

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

Task.Wait确实阻止了你当前的线程.根据MSDN:

Task.Wait Method

Waits for the Task to complete execution.

编辑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);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读