• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

限制并发线程数例程(C#)

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

按自己的想法实现的C#版本的限制并发线程数的例程,给有需要的读者

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

namespace WZDM.Test
{
    /// <summary>
    /// 限制并发线程数例程
    /// </summary>
    public class TestThread 
    {
        int _currentThreads = 0;
        int _maxThreads = 10;

        public void Test()
        {
            while (true)
            {
                //_maxThreads = new Random().Next(1, 10);
                for (int i=0; i<100; i++)
                {
                    // 在此进行数量限制
                    if (_currentThreads >= _maxThreads)
                        break;

                    // 开启线程
                    lock (typeof(TestThread))
                    {
                        _currentThreads++;
                        if (_currentThreads > _maxThreads)
                            _currentThreads = _maxThreads;

                        string currentInfo = string.Format("thread {0}/{1}", _currentThreads, _maxThreads);
                        Console.WriteLine(currentInfo + " start");
                        Thread thread = new Thread(new ParameterizedThreadStart(Run));
                        thread.Start(currentInfo);
                    }
                }

                System.Threading.Thread.Sleep(2000);
            }
        }

        // 线程任务
        void Run(object obj)
        {
            for (int i = 0; i < 100; i++)
            {
                Console.WriteLine("{0}:{1}", obj, i);
                Thread.Sleep(100);
            }
            Console.WriteLine("{0} finished", obj);


            lock (typeof(TestThread))
            {
                _currentThreads--;
                if (_currentThreads < 0)
                    _currentThreads = 0;
            }
        }
    }
}


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C#内存分配发布时间:2022-07-10
下一篇:
在C++中实现C#的delegate机制发布时间:2022-07-10
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap