线程无法使用CancellationToken执行清理

时间:2019-03-21 14:17:41

标签: c# multithreading

我有一个Windows服务,该服务会生成一些线程,并且我试图确保它们正确关闭。

服务定义为

    protected override void OnStart(string[] args)
    {
        eventLog1.WriteEntry("Service Started");
        logger.Info("Service Starting");

        docProcessors = new DocProcessor[NumberOfThreads];
        workerThreads = new Thread[NumberOfThreads];
        logger.Debug($"Service Starting {NumberOfThreads} Threads");
        for (int i = 0; i < NumberOfThreads; i++)
        {
            logger.Debug($"Service thread {i+1} starting");
            docProcessors[i] = new DocProcessor(i+1,eventLog1);
            bool b = ThreadPool.QueueUserWorkItem(new WaitCallback(docProcessors[i].StartProcess), cts.Token);
            logger.Debug($"Service thread {i+1} started");
        }
        logger.Info("Service Started");

    }

    protected override void OnStop()
    {
        logger.Info("Service Stopping");
        cts.Cancel();
        cts.Dispose();
        eventLog1.WriteEntry("Service Stopped");
        logger.Info("Service Stopped");
    }   

和这样的工人(减去实际工作...)

    public void StartProcess(object obj)
    {
        token = (CancellationToken)obj;

        token.Register(() =>
        {
            logger.Debug($"Thread {ThreadNumber} Cancel Requested ");
            isCancelled = true;
        });


        noticeLogger.Info($"StartProcess {threadNumber}");
        logger.Info($"StartProcess {threadNumber}");
        var stopwatch = new Stopwatch();
        while (KeepRunning())
        {


            if (KeepRunning())
            {
                int seconds = 30;                   
                logger.Trace($"{threadNumber} sleeping {seconds} seconds");
                Thread.Sleep(new TimeSpan(0, 0, seconds));
            }
        }

        logger.Info($"DocProcessor thread {ThreadNumber} complete");
        noticeLogger.Info($"DocProcessor thread {ThreadNumber} complete");

    }

当我停止服务时,通常会看到类似

2019-03-21 10:13:55.0403 INFO Service Stopping
2019-03-21 10:13:55.0403 DEBUG Thread 2 Cancel Requested
2019-03-21 10:13:55.0403 DEBUG Thread 1 Cancel Requested
2019-03-21 10:13:55.0403 INFO Service Stopped

但我从未见过类似的东西 “ DocProcessor线程1完成” 我想这意味着StartProcess方法永远不会运行完成。

另外,而且可能最重要的是,如果确实有工作在发生,那么它只会停在中间。

我假设我所做的事情根本不正确。

0 个答案:

没有答案