【问题标题】:Windows Service cannot start a Thread in Win 2003 ServerWindows 服务无法在 Win 2003 Server 中启动线程
【发布时间】:2009-11-12 08:13:54
【问题描述】:

我的 Windows 服务能够在 Win XP 中启动线程(使用 ThreadStart 委托),但在 Win 2003 Server 中它不能,它也没有抛出异常......线程根本没有启动。

我做了一个测试 Windows 服务,它在 (OnStart) 事件处理程序中具有相同的代码,它在 Win XP 和 Win 2003 Server 上都可以工作,这让我发疯,我不知道我原来的服务有什么问题,为什么它不能启动线程。

这是我的 Win Service 中出现问题的代码,以及在测试 Win Service 中运行良好的代码:

    private Thread trd;
    StreamWriter sw;
    int i = 0;


    protected override void OnStart(string[] args)
    {
        // TODO: Add code here to start your service.
        sw = new StreamWriter("c:\\TestingService.txt", true);

        trd = new Thread(new ThreadStart(this.LoopingThread));
        trd.IsBackground = false;
        trd.Priority = ThreadPriority.Highest;
        trd.Start();
    }

    protected override void OnStop()
    {
        // TODO: Add code here to perform any tear-down necessary to stop your service.
    }

    private void LoopingThread()
    {
        while (i < 100)
        {
            lock (sw)
            {
                sw.WriteLine("hello from thread i="+i.ToString());
                sw.Flush();
            }
            i++;
            Thread.Sleep(1000);
        }
    }

此代码在两个 Win 服务上“完全相同”。 我的原始服务(有问题)获得了对其他 DLL 的许多引用,其“使用”列表是:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
using System.Text;
using System.IO;
using System.Xml;
using System.Security.Principal;
using System.Reflection;
using System.Threading;
using System.Management;

以及与某些机密 DLL(第 3 方)相关的其他使用声明 但我实际上并没有创建任何对象......有效的代码正是我发布的。

我无法弄清楚为什么我的 Win 服务无法在 Win 2003 服务器上启动线程

【问题讨论】:

  • 为此在事件日志中添加了什么?它会给我们更多的线索来帮助你
  • 我有点困惑-您是说您发布的代码本身可以正常工作(在 Win2003 上),但是当您添加对第 3 方(和其他 DLL)的引用并使用声明表明它停止工作?

标签: windows-services multithreading


【解决方案1】:

在 OnStart() 方法的开头调用 System.Diagnostics.Debugger.Break() 并在调试中编译。启动服务时,系统会提示您启动调试会话。进入调试器后,从 Debug 菜单打开 Exceptions 对话框并检查 Thrown 列中的 Common Language Runtime Exceptions。如果抛出异常,您的服务将停止。

如果我不得不猜测,我会说你的线程没有启动的原因是因为它没有走那么远。根据您提供的代码,我会说 StreamWriter 的创建由于某种原因而失败。例如,您可能没有 Win 2003 Server 机器上 C 盘的写入权限。

【讨论】:

    【解决方案2】:

    这是以非常愚蠢的方式解决的! 我刚刚在我的 Windows 服务中创建了另一个类,将所有代码复制到其中,然后将 program.cs 中的代码创建在该类的实例中,而不是旧的服务类中。

    之后一切正常,我不知道发生了什么!

    感谢所有试图提供帮助的人

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-16
      • 1970-01-01
      • 2011-04-13
      • 2022-11-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多