c# 串口 应答式顺序下发命令 循环 间隔发送指令

c# 串口 应答式顺序下发命令 循环 间隔发送指令

实现原理

难点

  1. 多个命令放在list 内如何顺序发送
  2. 如果保证应答
  3. 如何保证命令之间的延时

解决方法

  1. 1 2 使用 while await Task.Delay(1000) 解决
  2. 应答 使用AutoResetEvent解决

相关文章推荐:

C#之使用AutoResetEvent实现线程的顺序执行

示例代码

internal class Program
    {
        private static readonly AutoResetEvent _autoResetEvent = new AutoResetEvent(false);

        private static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            Test();

            Console.ReadLine();
        }

        private static void Test()
        {
            SerialPort serialPort = new SerialPort("COM2");
            serialPort.Open();
            SerialPort serialPort1 = new SerialPort("COM3");
            serialPort1.ReceivedBytesThreshold = 6;
            serialPort1.DataReceived += ((se, ev) =>
            {
                byte[] respBytes = new byte[6];
                serialPort1.Read(respBytes, 0, 6);
                Console.WriteLine("COM3接收到的信息:" + Encoding.UTF8.GetString(respBytes) + "  " + respBytes.Length);
                _autoResetEvent.Set();
            });
            serialPort1.Open();

            List<string> list = new List<string>() { "aaaccc", "bbbccc", "cccaaa", "ddddaaa" };

            Task.Run(async () =>
            {
                int i = 0;
                while (true)
                {
                    await Task.Delay(1000);
                    Console.WriteLine("执行COM1指令");
                    serialPort.Write(Encoding.UTF8.GetBytes(list[i]), 0, 6);
                    i++;
                    if (i == list.Count)
                        i = 0;
                    _autoResetEvent.WaitOne();
                }
            });
        }
    }

其他思路

思路一:解决顺序执行

原文链接:https://www.cnblogs.com/cplemom/p/14290789.html

public static Task LoopAsync<T>(this IEnumerable<T> list, Func<T, Task> function)
{
    return Task.WhenAll(list.Select(function));
}

public async static Task<IEnumerable<TOut>> LoopAsyncResult<TIn, TOut>(this IEnumerable<TIn> list, Func<TIn, Task<TOut>> function)
{
    var loopResult = await Task.WhenAll(list.Select(function));

    return loopResult.ToList().AsEnumerable();
}

思路二:

代码出处:https://onebyone.icu/

private readonly int TimeoutInMilliseconds = 10000; //请求等待时长


public bool IsSuccess { get; set; }//默认false,如果接收结果则更改为true


private bool CheckResult()
{
    var s1 = new Stopwatch();//计时器
    s1.Start();
    do
    {
        if (!IsSuccess continue;
            IsSuccess = false;
        	return true;
    } while (TimeoutInMilliseconds > s1.ElapsedMilliseconds);

     return false;
}
posted @ 2021-07-07 15:23  AJun816  阅读(1408)  评论(0编辑  收藏  举报