【发布时间】: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