SerialPort.DataReceived在Windows服务/会话零中不起作用

时间:2019-01-08 01:04:44

标签: c# .net serial-port

永远不会在零会话中运行的C#.NET服务中调用DataReceived事件,但在当前用户会话中运行的控制台应用程序或服务中却不会这样做。 我缺少一些许可吗?

/// <summary>
        /// Opens the first avaliable COM port that matches the vid/pid
        /// </summary>
        public static bool OpenComDevice(string vid, string pid, out SerialPort serialPort)
        {
            serialPort = null;

            // find server com port
            var regPortNames = ComPortNames(vid, pid);
            foreach (string name in SerialPort.GetPortNames())
            {
                if (regPortNames.Contains(name))
                {
                    try
                    {
                        serialPort = new SerialPort(name);
                        serialPort.DtrEnable = true;
                        serialPort.Open();
                    }
                    catch
                    {
                        if (serialPort != null)
                        {
                            serialPort.Dispose();
                            serialPort = null;
                        }

                        continue;
                    }

                    break;
                }
            }

            return serialPort != null;
        }

private void Connect()
        {
            if (!Utils.OpenComDevice("239A", "801E", out serial)) return;
            DebugLog.Log("Connected: " + serial.PortName);

            serial.DataReceived += Serial_DataReceived;
            serial.PinChanged += Serial_PinChanged;
            serial.ErrorReceived += Serial_ErrorReceived;

            isConnected = true;
            ConnectedEvent?.Invoke(serial.PortName);
        }

1 个答案:

答案 0 :(得分:0)

在用于Windows服务的.NET中,您需要调用Dispatcher.Run()