C#按钮单击事件中的串行写入问题

C#按钮单击事件中的串行写入问题,c#,delegates,serial-port,C#,Delegates,Serial Port,我正试图解决C#到Arduino的串行通信问题。我想使用serial.Write()向Arduino发送两条(或更多)单独的消息。Arduino接收第一条消息。但不是第二条。Arduino接收第一个字符串,并在没有任何问题的情况下发回一条“已连接”消息。C#拾取“已连接”使用dataReceived事件。然后,Arduino从未收到第二条消息。我知道Arduino代码工作正常,因为它使用串行监视器工作正常。我了解了如何使用委托将接收到的数据返回到UI。然后,我尝试使用委托再次单击同一按钮,并使用

我正试图解决C#到Arduino的串行通信问题。我想使用serial.Write()向Arduino发送两条(或更多)单独的消息。Arduino接收第一条消息。但不是第二条。Arduino接收第一个字符串,并在没有任何问题的情况下发回一条“已连接”消息。C#拾取“已连接”使用dataReceived事件。然后,Arduino从未收到第二条消息。我知道Arduino代码工作正常,因为它使用串行监视器工作正常。我了解了如何使用委托将接收到的数据返回到UI。然后,我尝试使用委托再次单击同一按钮,并使用switch/case切换serialWrite消息但是,我认为委托只与方法一起工作,而不与事件一起工作.但是,我找不到足够的例子来真正理解它。我还尝试在点击事件中来回发送和接收消息,这也不起作用。我确实发现我可以从另一个按钮点击事件中触发第二条消息,并将其发送到Arduino。可能有更好的方法来完成我在这里尝试的操作。但是,我我还没找到…请帮忙

C#代码:


我的解决方案是排除“100”写入。我意识到这不是必需的,Arduino在收到一个传入字符串后仍然可以响应两次。

可能这
等待任务。延迟(1000);
?尝试
线程。睡眠(1000);
而不是
任务。延迟

   private void INIT_button_Click(object sender, EventArgs e)
    {
        code_window.Items.Clear();
        serialPort.WriteLine("100");  // This gets received
        Task.Delay(1000);
        serialPort.WriteLine("X1234Y23423Z134");  // This doesn't      
    }

    private void serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
    {
        string incoming_string = serialPort.ReadExisting();
        if (incoming_string.StartsWith("X"))
        {
            string X_value = incoming_string.Substring(1, incoming_string.IndexOf("Y") - 1);
            set_X_position(X_value);  //  runs with a delegate
        }
        else
        {
            set_text(incoming_string);  // set_text runs with delegate
        }
    }
    
    private void set_text(string text)
    {   
        //  All of this works great  
        //  A different method invokes the second line to a different textbox
        if (this.code_window.InvokeRequired)
        {
            update_from_Arduino update = new update_from_Arduino(set_text);
            this.Invoke(update, new object[] { text });
        }
        else
        {
            this.code_window.Items.Add(text);
        }
    }