c# 串口 應答式順序下發命令 循環 間隔發送指令
實現原理
難點
- 多個命令放在list 內如何順序發送
- 如果保證應答
- 如何保證命令之間的延時
解決方法
- 1 2 使用 while await Task.Delay(1000) 解決
- 應答 使用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();
}
思路二:
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;
}