首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C#循环节流

C#循环节流
EN

Stack Overflow用户
提问于 2013-01-23 16:22:39
回答 1查看 1.1K关注 0票数 7

初始情况

我正在开发一个.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

一个示例代码会非常有用的!

--这是我的解决方案/样本代码--

代码语言:javascript
复制
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);
        }
    }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-01-23 16:27:30

您可能想看看如何使用SemaphoreSlim类来节流访问队列的线程。

票数 7
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14484353

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档