C#-在第二个事件总是跳过第一个事件上执行SerialDataReceivedEventHandler

问题描述

我有使用COM4端口的条形码扫描仪。 每次扫描东西时,程序都会在第二次扫描后开始读取条形码。

因此,我建立了一个项目,尝试进行扫描,但没有任何反应。我尝试再次扫描(在此正在运行的项目中),它开始正常运行。

在项目顶部,我将端口声明为:

SerialPort port = new SerialPort();

我有一个定义端口的方法:

public void ScannerPortSetup()
{
        port.PortName = "COM4";               
        port.BaudRate = 9600;
        port.Handshake = Handshake.None;
        port.Parity = Parity.None;
        port.DataBits = 8;
        port.StopBits = StopBits.One;
        port.DtrEnable = true;
        port.ReadTimeout = 200;

        try
        {
            port.Open();
            
            if (port.IsOpen == true)
            {
                port.DataReceived += new SerialDataReceivedEventHandler(Recieve);
                
             }

            else
            {
                //print not opened
            }
        }

        catch (Exception e)
        {
            MessageBox.Show("Error on com4: " + e);
        }
 }

定义收到的操作的方法:

    private void Recieve(object sender,SerialDataReceivedEventArgs e)
    {

        String recieved_data = port.ReadExisting();
   
        this.Dispatcher.Invoke(() =>
        {
            if (currentScreenName == ApplicationPages.SkladisteScreen.ToString())
            {
                MessageBox.Show("scanned completed:  " + recieved_data);
            }
           

        }); 
    }

同样,我不知道为什么它在第一次发生时不触发,但是从第二次开始就可以正常工作。 我是否将MessageBox放在this.Dispatcher.Invoke()内还是Recieve方法的上方都没关系。似乎第一次没有触发Recieve。

有什么想法吗?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...