gpt4 book ai didi

C# 节流 For 循环

转载 作者:太空狗 更新时间:2023-10-29 20:21:01 29 4
gpt4 key购买 nike

初始情况

我正在开发 .NET Framework 4.0、C#、Winform 应用程序。应用程序将在 GridView 中列出(并测试)WebServiceOperations(目前有 60 个 DataRows => WebServiceOperations)。

目标

我必须通过单击一个按钮来测试/调用所有这些操作。每个操作都会创建一个类的新实例。在此类中,我调用 WebServiceOperation async 并等待结果。然后对结果进行验证。整个代码使用委托(delegate)和事件运行顺利。

现在是挑战/问题:单击该按钮时,我使用 for 循环 (int i = 0; i < gridViewWsOperations.RowCount; i++) => 换句话说,目前我正在“同时”对它们执行 60 个操作 => 服务器在同时处理 60 个请求时重载,我超时了。所以我需要以某种方式限制并发请求的数量,让我们同时说 10 个。考虑一下,for 循环(我必须使请求入队)与我使请求出队的方法(process_result 事件)不在同一个线程中。我尝试使用 ConcurrentQueue,因为这种类型的集合似乎是线程安全的。

链接

ConcurrentQueue at MSDN

示例代码真的很有帮助!

---这是我的解决方案/示例代码---

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.Concurrent;
using System.Threading;

namespace ConcurrentQueueSample
{
class Program
{
static SemaphoreSlim semaphoreSlim = new SemaphoreSlim(3);

static void Main(string[] args)
{
System.Timers.Timer timer = new System.Timers.Timer();
timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
timer.Interval = 1234;
timer.Enabled = true;
timer.Start();

for (int i = 0; i < 10; i++) new Thread(go).Start(i);
}

static void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
semaphoreSlim.Release();
}

static void go(object i)
{
Console.WriteLine("id: {0}", i);
semaphoreSlim.Wait();
Console.WriteLine("id: {0} is in", i);
Thread.Sleep(1250);
Console.WriteLine("id: {0} left!", i);
}
}
}

最佳答案

您可能想看看使用 SemaphoreSlim类来限制有权访问您的队列的线程。

关于C# 节流 For 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14484353/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com