Chr*_*utt 7 c# queue stack winforms concurrent-collections
初步情况
我正在开发.NET Framework 4.0,C#,Winform Application.应用程序将在GridView中列出(并测试)WebServiceOperations(当前有60个DataRows => WebServiceOperations).
目的
我只需点击一下按钮即可测试/调用所有这些操作.每个操作都会创建一个类的新实例.在这个类中,我调用WebServiceOperation异步并等待结果.结果随后得到验证.使用委托和事件,整个代码可以顺利运行.
现在谈到挑战/问题:当点击该按钮时,我使用for循环(int i = 0; i <gridViewWsOperations.RowCount; i ++)=>换句话说,目前我正在对它们进行60次操作'同时'=>服务器同时处理60个请求超载,我得到超时.所以我需要以某种方式限制结束请求的数量,让我们同时说10.考虑一下,for循环(我必须将请求排入队列)与我将请求出列的方法(process_result事件)不在同一个线程中.我尝试使用ConcurrentQueue,因为这种类型的集合似乎是线程安全的.
链接
示例代码真的会有所帮助!
---这是我的解决方案/示例代码---
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);
}
}
}
Run Code Online (Sandbox Code Playgroud)