Чтение одиночных байтов из SerialPort синхронно?

Я пытаюсь читать из последовательного порта по байту. В моем консольном приложении есть следующий код:

// Open the serial port in 115200,8N1
using (SerialPort serialPort = new SerialPort("COM1", 115200,
                                              Parity.None, 8,
                                              StopBits.One))
{
    serialPort.Open();

    for (; ; )
    {
        int result = serialPort.ReadByte();
        if (result < 0)
            break;

        Console.WriteLine(result);
    }
}

Я ожидаю, что это будет циклически повторяться, сбрасывая полученные байты на экран (игнорируйте на мгновение, что они будут напечатаны как целые числа; я займусь этим позже).

Однако он просто блокирует вызов ReadByte и ничего не происходит.

Я знаю, что мое последовательное устройство работает: если я использую Tera Term, я вижу данные. Если я использую событие DataReceived и вызываю SerialPort.ReadExisting, я могу видеть данные.

Однако меня не беспокоит производительность (по крайней мере, пока), и протокол, который я реализую, работает лучше, когда обрабатывается синхронно.

Итак: что я делаю не так? Почему ReadByte не возвращается?


person Roger Lipscombe    schedule 01.06.2009    source источник
comment
Это на WinForms, консоли или SmartDevice?   -  person Henk Holterman    schedule 01.06.2009
comment
Консольное приложение (но, возможно, позже WinForms); определенно не Compact Framework.   -  person Roger Lipscombe    schedule 01.06.2009
comment
Сам по себе этот код выглядит нормально ... можете ли вы предоставить образец кода, который вы пробовали и который работал (управляемый событиями)?   -  person jerryjvl    schedule 01.06.2009
comment
Может быть, попробовать какой-нибудь цикл с serialPort.BytesToRead ›0 - для отладки.   -  person Kamil    schedule 01.10.2012


Ответы (2)


Вы можете сделать асинхронное поведение синхронным, сделав что-то вроде этого и вызывая WaitForData() перед каждым чтением:

static SerialPort port;
static AutoResetEvent dataArrived = new AutoResetEvent(false);

static void Main(string[] args) {
  port = new SerialPort(...);
  port.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);
  port.Open();
  WaitForData(1000);
  int data = port.ReadByte();
  Console.WriteLine(data);
  Console.ReadKey();
}

static void WaitForData(int millisecondsTimeout) {
  dataArrived.WaitOne(millisecondsTimeout);
}

static void port_DataReceived(object sender, SerialDataReceivedEventArgs e) {
  dataArrived.Set();      
}

Этот ответ не такой «правильный», как поиск и решение основной проблемы, но может быть основой обходного пути.

Я видел некоторые странные вещи с классом SerialPort, включая описанное вами поведение. Имейте в виду, что событие DataReceived вызывается во вторичном потоке (см. MSDN). Вы можете немного повысить производительность, используя семантику lock () с Monitor.Wait () и .Pulse (), как описано в здесь

Если вы ленивы, вы также можете попробовать вставить строку Thread.Sleep () (например, 200 мс) прямо перед вызовом ReadByte, чтобы увидеть, имеет ли это значение. Также я мог бы поклясться, что однажды видел случай, когда SerialPort, который блокировал ReadByte () в консольном приложении, был перенесен в приложение WinForms без значимых изменений кода, и проблема исчезла. У меня не было возможности тщательно исследовать, но вы могли посмотреть, удастся ли вам больше в WinForms, а затем устранить неполадки оттуда.

Этот ответ немного запоздалый, но я подумал, что перезвоню следующему человеку, который столкнется с этим вопросом.

РЕДАКТИРОВАТЬ: Вот удобный WaitForBytes(count, timeout) метод расширения, который хорошо справляется с фильтрацией описанного вами поведения "бесконечной блокировки".

Использование: port.WaitForBytes(1) для ожидания поступления 1 байта данных. Или для уменьшения накладных расходов используйте вместо этого SerialPortWatcher.WaitForBytes(n).

using System;
using System.Diagnostics;
using System.IO.Ports;
using System.Threading;

public static class SerialPortExtensions {

  /// <summary>
  /// Wait for a specified number of bytes to arrive on the serial port, or until a timeout occurs.
  /// </summary>
  /// <param name="port">Serial port on which bytes are expected to arrive.</param>
  /// <param name="count">Number of bytes expected.</param>
  /// <param name="millisecondsTimeout">Maximum amount of time to wait.</param>
  /// <exception cref="TimeoutException">Thrown if <paramref name="count"/> bytes are not received
  /// within <paramref name="millisecondsTimeout"/> milliseconds.</exception>
  /// <exception cref="ArgumentNullException">Thrown if <paramref name="port"/> is null.</exception>
  /// <exception cref="ArgumentOutOfRangeException">Thrown if either <paramref name="count"/> or
  /// <paramref name="millisecondsTimeout"/> is less than zero.</exception>
  /// <exception cref="InvalidOperationException">Thrown if the serial port is closed.</exception>
  /// <remarks>This extension method is intended only as an ad-hoc aid.  If you're using it a lot,
  /// then it's recommended for performance reasons to instead instantiate a
  /// <see cref="SerialPortWatcher"/> instance for the lifetime of your SerialPort.</remarks>
  public static void WaitForBytes(this SerialPort port, int count, int millisecondsTimeout) {

    if (port == null) throw new ArgumentNullException("port");
    if (port.BytesToRead >= count) return;

    using (var watcher = new SerialPortWatcher(port)) {
      watcher.WaitForBytes(count, millisecondsTimeout);
    }

  }

  /// <summary>
  /// Wait for a specified number of bytes to arrive on the serial port, or until a timeout occurs.
  /// </summary>
  /// <param name="port">Serial port on which bytes are expected to arrive.</param>
  /// <param name="count">Number of bytes expected.</param>
  /// <exception cref="ArgumentNullException">Thrown if <paramref name="port"/> is null.</exception>
  /// <exception cref="ArgumentOutOfRangeException">Thrown if either <paramref name="count"/> or
  /// <paramref name="millisecondsTimeout"/> is less than zero.</exception>
  /// <exception cref="InvalidOperationException">Thrown if the serial port is closed.</exception>
  /// <exception cref="TimeoutException">Thrown if <paramref name="count"/> bytes are not received
  /// within the number of milliseconds specified in the <see cref="SerialPort.ReadTimeout"/> property
  /// of <paramref name="port"/>.</exception>
  /// <remarks>This extension method is intended only as an ad-hoc aid.  If you're using it a lot,
  /// then it's recommended for performance reasons to instead instantiate a
  /// <see cref="SerialPortWatcher"/> instance for the lifetime of your SerialPort.</remarks>
  public static void WaitForBytes(this SerialPort port, int count) {
    if (port == null) throw new ArgumentNullException("port");
    WaitForBytes(port, count, port.ReadTimeout);
  }

}

/// <summary>
/// Watches for incoming bytes on a serial port and provides a reliable method to wait for a given
/// number of bytes in a synchronous communications algorithm.
/// </summary>
class SerialPortWatcher : IDisposable {

  // This class works primarilly by watching for the SerialPort.DataReceived event.  However, since
  // that event is not guaranteed to fire, it is neccessary to also periodically poll for new data.
  // The polling interval can be fine-tuned here.  A higher number means less wasted CPU time, while
  // a lower number decreases the maximum possible latency.
  private const int POLL_MS = 30;

  private AutoResetEvent dataArrived = new AutoResetEvent(false);
  private SerialPort port;

  public SerialPortWatcher(SerialPort port) {
    if (port == null) throw new ArgumentNullException("port");
    this.port = port;
    this.port.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);
  }

  public void Dispose() {
    if (port != null) {
      port.DataReceived -= port_DataReceived;
      port = null;
    }
    if (dataArrived != null) {
      dataArrived.Dispose();
      dataArrived = null;
    }
  }

  void port_DataReceived(object sender, SerialDataReceivedEventArgs e) {

    // This event will occur on a secondary thread.  Signal the waiting thread (if any).
    // Note: This handler could fire even after we are disposed.

    // MSDN documentation describing DataReceived event:
    // http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.datareceived.aspx

    // Links discussing thread safety and event handlers:
    // https://stackoverflow.com/questions/786383/c-events-and-thread-safety
    // http://www.codeproject.com/Articles/37474/Threadsafe-Events.aspx

    // Note that we do not actually check the SerialPort.BytesToRead property here as it
    // is not documented to be thread-safe.

    if (dataArrived != null) dataArrived.Set();

  }

  /// <summary>
  /// Blocks the current thread until the specified number of bytes have been received from the
  /// serial port, or until a timeout occurs.
  /// </summary>
  /// <param name="count">Number of bytes expected.</param>
  /// <param name="millisecondsTimeout">Maximum amount of time to wait.</param>
  /// <exception cref="ArgumentOutOfRangeException">Thrown if either <paramref name="count"/> or
  /// <paramref name="millisecondsTimeout"/> is less than zero.</exception>
  /// <exception cref="InvalidOperationException">Thrown if the serial port is closed, or if this
  /// <see cref="SerialPortWatcher"/> instance has been disposed.</exception>
  /// <exception cref="TimeoutException">Thrown if <paramref name="count"/> bytes are not received
  /// within the number of milliseconds specified in the <see cref="SerialPort.ReadTimeout"/> property
  /// of <paramref name="port"/>.</exception>
  public void WaitForBytes(int count, int millisecondsTimeout) {

    if (count < 0) throw new ArgumentOutOfRangeException("count");
    if (millisecondsTimeout < 0) throw new ArgumentOutOfRangeException("millisecondsTimeout");
    if (port == null) throw new InvalidOperationException("SerialPortWatcher has been disposed.");
    if (!port.IsOpen) throw new InvalidOperationException("Port is closed");

    if (port.BytesToRead >= count) return;

    DateTime expire = DateTime.Now.AddMilliseconds(millisecondsTimeout);

    // Wait for the specified number of bytes to become available.  This is done primarily by
    // waiting for a signal from the thread which handles the DataReceived event.  However, since
    // that event isn't guaranteed to fire, we also poll for new data every POLL_MS milliseconds.
    while (port.BytesToRead < count) {
      if (DateTime.Now >= expire) {
        throw new TimeoutException(String.Format(
          "Timed out waiting for data from port {0}", port.PortName));
      }
      WaitForSignal();
    }

  }

  // Timeout exceptions are expected to be thrown in this block of code, and are perfectly normal.
  // A separate method is used so it can be marked with DebuggerNonUserCode, which will cause the
  // debugger to ignore these exceptions (even if Thrown is checkmarked under Debug | Exceptions).
  [DebuggerNonUserCode]
  private void WaitForSignal() {
    try {
      dataArrived.WaitOne(POLL_MS);
    } catch (TimeoutException) { }
  }

}
person rkagerer    schedule 30.04.2011
comment
Спасибо. Ожидание полученных данных помогло мне обойти проблему. - person cheedep; 25.04.2012

Я думаю, что ваш цикл прерывается при первом запуске (при запуске), когда в буфере нет данных.

if (result < 0)
    break;

Поздний цикл не запущен, и вы не видите данных на консоли.

person Kamil    schedule 01.10.2012