执行SerialPort.Close()时线程卡住

时间:2014-12-12 12:59:25

标签: c# .net multithreading serial-port

当我想要关闭gsm终端的串口时,我遇到了一个问题,即我的应用程序中的线程遇到了死锁。这个问题众所周知herehere,但这些主题中的所有建议都没有帮助我。

/// <summary>
///     Closes the COM port, prevents reading and writing
/// </summary>
public void Stop()
{
    Debug.WriteLine("stop called");
    var block = true;
    var bgw = new BackgroundWorker
    {
        WorkerReportsProgress = false,
        WorkerSupportsCancellation = false,
    };

    bgw.DoWork += (s, e) =>
    {
        if (!CanAccessPort())
            return;

        try
        {
            _serialPort.DataReceived -= Read;
            GC.ReRegisterForFinalize(_serialPort.BaseStream);
            _serialPort.Close();
            _isOpen = false;

        }
        catch (Exception ex)
        {
            throw new Exception(PORTERROR, ex);
        }
    };

    bgw.RunWorkerCompleted += (s, e) =>
    {
        Debug.WriteLine("block is set to false =)");
        block = false;
    };

    bgw.RunWorkerAsync();
    while (block)
        Thread.Sleep(250);
}

执行_serialPort.Close()时,上面的代码会永远运行。作为推荐的建议,我读到了在单独的线程中运行关闭操作。我尝试了BackgroundWorkerThread类,但没有任何效果。使用另一个线程中建议的AutoResetEvent也不起作用。在关闭端口之前,我正在向它发送一些命令并收到几个结果,但它不会关闭。当我运行一个启动端口的简单命令行程序,读取数据并尝试关闭它时,一切正常,甚至没有线程。

什么可能导致死锁?我几乎没有在其他几乎所有答案中提到任何GUI相关的东西。

DataReceived事件处理程序代码:

/// <summary>
///     Reads input from the COM interface and invokes the corresponding event depending on the input
/// </summary>
private void Read(object sender, SerialDataReceivedEventArgs e)
{
    var buffer = new char[1024];
    var counter = 0;
    _keepRunning = true;
     if (_timeout == null)
     {
        // timeout must be at least 3 seconds because when sending a sms to the terminal the receive notification (+CSDI) can be lost with less timeout 
        _timeout = new Timer(3000);
        _timeout.Elapsed += (s, ev) =>
        {
            _keepRunning = false;
            _timeout.Stop();
        };
    }
    _timeout.Start();

    // cancel condition: no more new data for 3 seconds or "OK"/"ERROR" found within the result
    while (_keepRunning)
    {
        var toRead = _serialPort.BytesToRead;
        if (toRead == 0)
        {
            Thread.Sleep(100);
            continue;
        }
        _timeout.Stop();
        _timeout.Start();

        counter += _serialPort.Read(buffer, counter, toRead);

        // ok or error found in result string
        var tmp = new string(buffer).Replace("\0", "").Trim();
        if (tmp.EndsWith("OK") || tmp.EndsWith("ERROR"))
        {
            _timeout.Stop();
            _keepRunning = false;
        }
    }

    // remove empty array slots from the back
    var nullTerminalCounter = 0;
    for (var i = buffer.Length - 1; i != 0; i--)
    {
        if (buffer[i] == '\0')
        {
            nullTerminalCounter++;
            continue;
        }
        break;
    }
    Array.Resize(ref buffer, buffer.Length - nullTerminalCounter);
    var str = new String(buffer).Trim();

    // result must be something different than incoming messages (+CMTI: \"MT\", 25)
    if (!((str.StartsWith("+CMTI") || str.StartsWith("+CSDI")) && str.Length < 20))
    {
        // when an incoming message is received, it does not belong to the command issued, so result has not yet arrived, hence port is still blocked!
        _isBlocked = false;
        Debug.WriteLine("port is unblocked");
    }


    var args = new CommandReturnValueReceivedEventArgs
    {
        ResultString = str
    };
    OnCommandReturnValueReceived(this, args);
}

2 个答案:

答案 0 :(得分:2)

    if (toRead == 0)
    {
        Thread.Sleep(100);
        continue;
    }

此代码是死锁的基本来源。 SerialPort.Close()的规则是,当SerialPort的所有事件处理程序都不活动时,它只能关闭串行端口。问题是,您的DataReceived事件处理程序几乎始终处于活动状态,等待数据。这不是该活动的预期用途。您应该读取串行端口中可用的任何内容,通常将字节附加到缓冲区并取出。当有更多字节可用时,事件再次触发。

   while (_keepRunning)

看起来你发现了这个问题,并试图用Timer修复它。这也不起作用,以非常 ratty的方式调试非常困难。 bool 变量不是正确的同步原语,如ManualResetEvent。当您定位x86并运行程序的Release版本时,while()循环将不会看到_keepRunning变量变为 false 。它启用了抖动优化器,它很容易将变量存储在cpu寄存器中。需要声明变量 volatile 来抑制优化。

怀疑,但无法保证,使用 volatile 可以解决您的问题。并且您可能希望在调用Close()之前将_keepRunning设置为 false ,这样就不会出现超时延迟。

然而,指出了更具结构性的解决方案。重写DataReceived事件处理程序,使其永远不会循环等待数据。鉴于这似乎是与调制解调器通信的代码,简单的_serialPort.ReadLine()调用应该是所有必需的。

答案 1 :(得分:0)

如果我确保OpenClose永远不会被任何线程同时调用,那么我已经离开了这些问题。我是通过使用锁来完成的。

本质如下。

lock(_port)
    _port.Open(.....);

...

lock(_port)
    _port.Close(.....);