c# 多线程的使用
需求描述 需要定期获取设备的状态 目前需要ping的设备只有 200个左右
耗时 177.429 秒
Stopwatch sw = new Stopwatch(); sw.Start(); try { var list= _assetinfoService.GetLists(ip:"true"); for (int i = 0; i < list.Count; i++) { var isTrue = CommonHelper.PingIp(list[i].IP4); list[i].QYZT= isTrue ? "1" : "2"; } _assetinfoService.BathUpdate(list); } catch (Exception ex) { return Fail("失败,", ex.Message); } sw.Stop(); return Success(@"成功{sw.ElapsedMilliseconds}ms"+ sw.ElapsedMilliseconds);
现在用50个线程代码跑一下
Stopwatch sw = new Stopwatch(); sw.Start(); try { var list = _assetinfoService.GetLists(ip: "true"); //设置最大并行线程数 int maxThreads = 50; // 使用 SemaphoreSlim 限制并行线程数量 SemaphoreSlim semaphore = new SemaphoreSlim(maxThreads); // 创建任务列表 List<Task> tasks = new List<Task>(); // 遍历设备列表并为每个设备创建一个任务 foreach (var item in list) { // 等待可用的信号量 await semaphore.WaitAsync(); // 创建任务并将其添加到任务列表 Task task = Task.Run(async () => { string ip = item.IP4; bool isPingable = false; try { Ping ping = new Ping(); PingReply reply = await ping.SendPingAsync(ip); if (reply.Status == IPStatus.Success) { isPingable = true; } } catch (PingException) { // 处理 ping 异常 } item.QYZT = isPingable ? "1" : "2"; // 释放信号量 semaphore.Release(); }); tasks.Add(task); } // 等待所有任务完成 await Task.WhenAll(tasks); _assetinfoService.BathUpdate(list); } catch (Exception ex) { return Fail("失败,", ex.Message); } sw.Stop(); return Success(@"成功{sw.ElapsedMilliseconds}ms" + sw.ElapsedMilliseconds);
耗时:20秒