why is access to com port denied?

后端 未结 5 1673
小蘑菇
小蘑菇 2020-12-06 17:13

the code:

static void Main(string[] args)
{
    Console.WriteLine(\"Memory mapped file reader started\");

    using (var file = MemoryMappedFile.OpenExistin         


        
5条回答
  •  感动是毒
    2020-12-06 17:27

    Hans' answer supercedes this one; I am leaving it for context and informational purposes only.


    You need to close the port when you are done with it. The garbage collector is not collecting the first SerialPort object before you try to open another handle to it. Change this code:

    SerialPort port = new SerialPort("COM2", 9600, Parity.None, 8, StopBits.One);
    port.Open();
    port.Write(reader.ReadElementContentAsString() + ",");
    

    To:

    using (SerialPort port = new SerialPort("COM2", 9600, Parity.None, 8, StopBits.One))) 
    {
        port.Open();
        port.Write(reader.ReadElementContentAsString() + ",");
    }
    

提交回复
热议问题