why is access to com port denied?

后端 未结 5 1672
小蘑菇
小蘑菇 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:48

    In addition to Hans' answer:

    I had the same problem and played around a bit with some sleep times between opening and closing the serial port. In my case 250 ms were sufficient. Maybe this will help out somebody out there.

    EDIT:

    I optimized my solution and this is what I came up with:

    int maxRetries = 20;
    const int sleepTimeInMs = 50;
    string loggingMessage = string.Empty;
    
    while (maxRetries > 0)
    {
        try
        {
            loggingMessage = "Opening serial port '" + mSerialPort.PortName + "'...";
            mSerialPort.Open();
            loggingMessage += "Succeeded.";
            IOLogger.LogInfo(loggingMessage);
        }
        catch (UnauthorizedAccessException unauthorizedAccessException)
        {
            maxRetries--;
            loggingMessage += "Failed (UnauthorizedAccessException): ";
            IOLogger.LogError(string.Format(loggingMessage + unauthorizedAccessException.Message + " -> Retrying in about {0} milliseconds...", sleepTimeInMs));
            Thread.Sleep(sleepTimeInMs);
        }
        catch (Exception exception)
        {
            loggingMessage += "Failed: ";
            IOLogger.LogError(loggingMessage + exception.Message);
        }
    }
    

    You can play around with the sleepTimeInMs and/or the maxRetries. I have chosen those values because they seemed to be sufficient in any needed use case.

提交回复
热议问题