简体   繁体   English

如何从 c# 中的两个不同应用程序访问串行端口

[英]How to access serial port from two different application in c#

I am using three WCF services, one to monitor the swipe card reader using serial port which receives data when user swipes the card.我正在使用三个 WCF 服务,一个使用串行端口监控刷卡读卡器,当用户刷卡时接收数据。 Data is then sent to another service which validates data and calls other service to open the gate for the user which associate to that swipe port.然后将数据发送到另一个服务,该服务验证数据并调用其他服务为与该刷卡端口关联的用户打开大门。

Since serial port is already opened and monitored by first WCF service, another service can't access the port to send command to open the door.由于串口已经被第一个WCF服务打开并监控,其他服务无法访问该端口发送开门命令。 When I try to fix this by creating a Singleton class around swipe port object, I can able to get the same object but state is not maintained insense the port says it's not opened but actually it is opened through first service. When I try to fix this by creating a Singleton class around swipe port object, I can able to get the same object but state is not maintained insense the port says it's not opened but actually it is opened through first service.

I just placed my port class.我刚刚放置了我的端口 class。 Any idea or suggestion please.请有任何想法或建议。

public class Port : SerialPort
{     
    public Port(string port) : base(port)
    {
    }

    public static Port Instance
    {
        get { return Nested.myPort; }
    }

    class Nested
    {
        static Nested() { }

        internal static Port swipePort;

        public static Port myPort
        {
            get
            {
                if (swipePort == null)
                    swipePort = new Port("COM4");

                if (!swipePort.IsOpen)
                    swipePort.Open();
                return swipePort;
            }
        }
    }
}

The same port cannot be opened twice.同一个端口不能打开两次。 I would suggest that one WCF service is responsible for communicating over the serial port and the others talk to that service.我建议一个 WCF 服务负责通过串行端口进行通信,而其他服务则与该服务通信。 Use client certificates or another authentication scheme so that calls to the service cannot result in unauthorised "Open Door" requests, for example.例如,使用客户端证书或其他身份验证方案,以便对服务的调用不会导致未经授权的“开门”请求。

Your example above creates a static instance of the port but static instances are only "static" in the context of the same AppDomain.您上面的示例创建了端口的 static 实例,但 static 实例仅在同一 AppDomain 的上下文中是“静态的”。 Depending on your hosting model, the two WCF services could be in different AppDomains.根据您的托管 model,两个 WCF 服务可能位于不同的 AppDomain 中。 Also, reads and writes to serial ports are not thread-safe so you will encounter problems using a SerialPort in this manner.此外,对串行端口的读写不是线程安全的,因此以这种方式使用 SerialPort 会遇到问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM