相关文章推荐:
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; }