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

╄→гoц情女王★ 提交于 2019-12-24 00:39:25

问题


I am using three WCF services, one to monitor the swipe card reader using serial port which receives data when user swipes the card. 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. 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. 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;
            }
        }
    }
}

回答1:


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. 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. Depending on your hosting model, the two WCF services could be in different AppDomains. Also, reads and writes to serial ports are not thread-safe so you will encounter problems using a SerialPort in this manner.



来源:https://stackoverflow.com/questions/6788381/how-to-access-serial-port-from-two-different-application-in-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!