无法停止使用后台工作程序的Windows服务

时间:2015-07-09 12:09:07

标签: c# service windows-services thread-safety

我有一个读卡器Windows服务,使用后台工作程序重复调用一个函数。

问题是服务无法停止。

我收到此错误:error 1061 the service cannot accept control messages at this time

我试过了

new BackgroundWorker { WorkerSupportsCancellation = true };
BackgroundWorker worker = (BackgroundWorker)sender;
while (!worker.CancellationPending)

this.RequestAdditionalTime(20000);

这是代码:

protected override void OnStart(string[] args)
{   
    try
    {
        cardReaderEventLog.WriteEntry("Card reader service is in start-pending status.", EventLogEntryType.Information);

        #region setup Card Reader events
        BackgroundWorker bw = new BackgroundWorker { WorkerSupportsCancellation = true };

        bw.DoWork += new DoWorkEventHandler(bw_DoWork);
        serviceStop = false;
        bw.RunWorkerAsync();
        #endregion

        cardReaderEventLog.WriteEntry("Card reader service started.", EventLogEntryType.Information);
    }
    catch (CardReaderNotDetectedException crndEx)
    {
        cardReaderEventLog.WriteEntry(crndEx.ToString(), EventLogEntryType.Error);
        if (crndEx.InnerException != null)
            cardReaderEventLog.WriteEntry(crndEx.InnerException.ToString(), EventLogEntryType.Error);
    }
    catch (Exception ex)
    {
        cardReaderEventLog.WriteEntry(ex.ToString(), EventLogEntryType.Error);
        if (ex.InnerException != null)
            cardReaderEventLog.WriteEntry(ex.InnerException.ToString(), EventLogEntryType.Error);
        Environment.Exit(1);
        //throw;
    }
}


protected override void OnStop()
{
    serviceStop = true;

    DisconnectCardReader();
    backgroundWorker.CancelAsync();
    backgroundWorker.Dispose();
    this.RequestAdditionalTime(20000);
    // Update the service state to Running.
    ServiceStatus serviceStatus = new ServiceStatus();
    serviceStatus.dwCurrentState = ServiceState.SERVICE_STOPPED;
    SetServiceStatus(this.ServiceHandle, ref serviceStatus);
    cardReaderEventLog.WriteEntry("Card reader service stopped.", EventLogEntryType.Information);
}

protected void bw_DoWork(object sender, DoWorkEventArgs e)
{
    BackgroundWorker worker = (BackgroundWorker)sender;
    while (!worker.CancellationPending)
    {
        DisconnectCardReader();
        try
        {
            InitializeSmartCardWrapper();
        }
        catch (CardReaderNotDetectedException crndEx)
        {
            cardReaderEventLog.WriteEntry(crndEx.ToString(), EventLogEntryType.Error);
            if (crndEx.InnerException != null)
                cardReaderEventLog.WriteEntry(crndEx.InnerException.ToString(), EventLogEntryType.Error);
        }

        System.Threading.Thread.Sleep(10000);
    }
    // Do something while waiting for events

}

0 个答案:

没有答案