初始情况
我正在开发一个.NET Framework4.0,C#,。应用程序将在一个WebServiceOperations中列出(并测试) GridView (目前有60 DataRows => WebServiceOperations)。
目标
我必须通过单击一个按钮来测试/调用所有这些操作。每个操作都会创建一个类的新实例。在这个类中,我调用WebServiceOperation异步并等待结果。结果是被验证。使用委托和事件,整个代码工作平稳。
现在到了问题/问题:当单击该按钮时,我使用一个for循环(int = 0;i< gridViewWsOperations.RowCount;i++) =>,换句话说,目前我在它们‘同时’触发60个操作--服务器得到重载,同时处理60个请求,并得到超时。因此,我需要以某种方式控制并发请求的数量,比如10次请求。考虑一下,for循环(在这里我必须对请求进行排队)与方法(process_result事件)不是同一个线程,方法是将请求排出队列。我尝试使用ConcurrentQueue,因为这种类型的集合似乎是线程安全的。
链接
ConcurrentQueue在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);
}
}
}发布于 2013-01-23 16:27:30
您可能想看看如何使用SemaphoreSlim类来节流访问队列的线程。
https://stackoverflow.com/questions/14484353
复制相似问题