我的服务是由 wix 安装的,并且可以正常启动,并且确实像我想要的那样工作,直到我在我的服务中添加了一个线程,所以我可能没有正确关闭线程
这里是服务
public class WCFWindowsService : ServiceBase
{
public ServiceHost serviceHost = null;
public WCFWindowsService()
{
// Name the Windows Service
ServiceName = "ServiceName";
}
public static void Main()
{
ServiceBase.Run(new WCFWindowsService());
}
protected override void OnStart(string[] args)
{
ThreadTheClass T = new ThreadTheClass();
if (serviceHost != null)
{
serviceHost.Close();
}
Thread _thread = new Thread(T.ThreadMain);
_thread = new Thread(T.ThreadMain);
_thread.Start();
serviceHost = new ServiceHost(typeof(ProjectWCF.WCFService));
serviceHost.Open();
}
protected override void OnStop()
{
ThreadTheClass T = new ThreadTheClass();
if (serviceHost != null)
{
WCFWindowsService ThreadPost = new WCFWindowsService();
T.ThreadStop();
serviceHost.Close();
serviceHost = null;
}
}
}
和线程类
class ThreadTheClass
{
System.Threading.Timer MyTimer;
public void ThreadMain()
{
int Minutes = 2;
MyTimer = new System.Threading.Timer((s) =>
{
Logic();
}
, null, 5000, Minutes * 100 * 60);
}
public void ThreadStop()
{
MyTimer.Dispose();
}
void Logic()
{
//do things every two minutes
}
当我在控制台程序中尝试这个时,我不知道什么是错误的原因,ThreadStop()
工作正常并关闭了线程,为什么它不能在 Windows 服务中关闭?
当我尝试停止已安装的服务时出现此错误