⭐Unity 实现每秒发送一个命令的需求

这个方法是异步的,调用它时需要使用await关键字,例如await SendCommandsAsync();

这要求调用方法的上下文也是异步的。如果你在一个非异步的上下文中需要调用它,可以考虑使用.Wait().Result,不推荐这么做,因为它可能会导致死锁。

using System.Threading.Tasks;

public async Task SendCommandsAsync()
{
    string[] commands = new string[] {
        "00 03 0D 0A",
        "01 03 0D 0A",
        "02 03 0D 0A",
        "03 03 0D 0A",
        "04 03 0D 0A",
        "05 03 0D 0A",
        "06 03 0D 0A",
        "07 03 0D 0A",
        "08 03 0D 0A",
        "09 03 0D 0A"
    };

    foreach (var command in commands)
    {
        MyPorts._instance.btnSend(command);  //这是我的发送命令 
        await Task.Delay(1000); // 等待1000毫秒(1秒)
    }
}