简体   繁体   中英

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. 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;
            }
        }
    }
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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