在我实现Thread后,我的Windows服务无法停止

时间:2013-01-30 08:02:49

标签: c# multithreading windows-services

我的服务是由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服务中关闭?

当我尝试停止已安装的服务时出现此错误 enter image description here

1 个答案:

答案 0 :(得分:1)

最明显的错误出现在OnStop

ThreadTheClass T = new ThreadTheClass();

这是创建ThreadTheClass实例。其中MyTimer将为null

相反,在您的OnStart方法中,您需要存储您在其中创建的实例,以便OnStop可以访问同一个实例。

ThreadTheClass T;

 protected override void OnStart(string[] args)
    {
        T = new ThreadTheClass();

            if (serviceHost != null)
            {
                serviceHost.Close();
            }
            T.ThreadMain();

            serviceHost = new ServiceHost(typeof(ProjectWCF.WCFService));
            serviceHost.Open(); 
    }

    protected override void OnStop()
    {
            if (serviceHost != null)
            {
                WCFWindowsService ThreadPost = new WCFWindowsService();

                T.ThreadStop();


                serviceHost.Close();
                serviceHost = null;
            }
    }

我还删除了创建(2!)new Thread s的代码 - 因为ThreadMain只是建立一个计时器然后退出,没有理由把它放在自己的线程上。 / p>