如果端口已在Mono中打开,则C#SerialPort.Open()不会引发异常 [英] C# SerialPort.Open() does not throw an exception if port is already open in Mono

查看:284
本文介绍了如果端口已在Mono中打开,则C#SerialPort.Open()不会引发异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Windows和Ubuntu上的Mono之间发现SerialPort.Open()的实现有所不同.这是我当前的实现:

I am finding a difference in the implementation of SerialPort.Open() between Windows and Mono on Ubuntu. Here is my current implementation:

        if (serPort.IsOpen)
        {
            serPort.Close();
        }

        serPort.BaudRate = Convert.ToInt32(baudRateCmbBox.Text);
        serPort.PortName = serPortCmbBox.Text;

        try
        {
            serPort.Open();
        }
        catch
        {
            return false;
        }

        return true;

在Windows中,如果我打开了另一个具有相同串行端口的程序,则将引发异常,并且该函数返回false.但是,在Mono中,无论另一个程序是否已经打开了串行端口,串行端口仍然会打开.它甚至可以与其他程序同时读取和写入串行端口.

In Windows, if I have another program with the same serial port open, then an exception is thrown and the function returns false. However, in Mono, the serial port still gets opened, regardless of whether or not another program already has the serial port open. It even reads and writes to the serial port at the same time as the other program.

所以问题是,有没有一种方法既可以在Windows中运行,又可以在Mono中运行,可以让我检查是否另一个程序已经打开了串行端口?

So the question is, is there a way that will work both in Windows and in Mono that will allow me to check if another program already has the serial port open?

推荐答案

在POSIX中,此行为归因于不同的文件锁定语义:许多进程可以访问同一文件.如果您要在Windows的Mono上运行代码,则会看到与Microsoft .Net相同的行为.

In POSIX this behaviour is due to different file locking semantics: many processes can access the same file. If you'd run your code on Mono on Windows, you would see the same behaviour as Microsoft .Net is showing.

要在Linux上以相同的方式工作,请 open_serial() Mono本机帮助程序中的方法必须在打开后获取 flock()文件描述符.

To work in the same way on Linux, open_serial() method in Mono native helper would have to acquire flock() on the opened file descriptor.

这篇关于如果端口已在Mono中打开,则C#SerialPort.Open()不会引发异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆