开启辅助访问 切换到宽版

精易论坛

 找回密码
 注册

QQ登录

只需一步,快速开始

用微信号发送消息登录论坛

新人指南 邀请好友注册 - 我关注人的新帖 教你赚取精币 - 每日签到


求职/招聘- 论坛接单- 开发者大厅

论坛版规 总版规 - 建议/投诉 - 应聘版主 - 精华帖总集 积分说明 - 禁言标准 - 有奖举报

查看: 1447|回复: 4
收起左侧

[C#源码] C#限制并发线程数例程

[复制链接]

结帖率:61% (35/57)
发表于 2013-7-23 08:34:04 | 显示全部楼层 |阅读模式   海南省海口市
按自己的想法实现的C#版本的限制并发线程数的例程,给有需要的读者
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.Threading;

  5. namespace WZDM.Test
  6. {
  7. /// <summary>
  8. /// 限制并发线程数例程
  9. /// </summary>
  10. public class TestThread
  11. {
  12. int _currentThreads = 0;
  13. int _maxThreads = 10;

  14. public void Test()
  15. {
  16. while (true)
  17. {
  18. //_maxThreads = new Random().Next(1, 10);
  19. for (int i=0; i<100; i++)
  20. {
  21. // 在此进行数量限制
  22. if (_currentThreads >= _maxThreads)
  23. break;

  24. // 开启线程
  25. lock (typeof(TestThread))
  26. {
  27. _currentThreads++;
  28. if (_currentThreads > _maxThreads)
  29. _currentThreads = _maxThreads;

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

  36. System.Threading.Thread.Sleep(2000);
  37. }
  38. }

  39. // 线程任务
  40. void Run(object obj)
  41. {
  42. for (int i = 0; i < 100; i++)
  43. {
  44. Console.WriteLine("{0}:{1}", obj, i);
  45. Thread.Sleep(100);
  46. }
  47. Console.WriteLine("{0} finished", obj);

  48. lock (typeof(TestThread))
  49. {
  50. _currentThreads--;
  51. if (_currentThreads < 0)
  52. _currentThreads = 0;
  53. }
  54. }
  55. }
  56. }
复制代码

结帖率:57% (13/23)
发表于 2013-7-23 08:55:10 | 显示全部楼层   广东省惠州市
楼主刷屏了哦,不过还差一主题
回复 支持 反对

使用道具 举报

结帖率:50% (1/2)
发表于 2013-7-23 08:46:06 | 显示全部楼层   河北省秦皇岛市
跟着内存学?你能说的详细点么
回复 支持 反对

使用道具 举报

结帖率:50% (1/2)
发表于 2013-7-23 08:43:30 | 显示全部楼层   河北省秦皇岛市
楼主,我不怎么想看教学视频,你有什么C#的学习资料么?

点评

嘻嘻 跟着内存学   海南省海口市  发表于 2013-7-23 08:44
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则 致发广告者

发布主题 收藏帖子 返回列表

sitemap| 易语言源码| 易语言教程| 易语言论坛| 诚聘英才| 易语言模块| 手机版| 广告投放| 精易论坛
拒绝任何人以任何形式在本论坛发表与中华人民共和国法律相抵触的言论,本站内容均为会员发表,并不代表精易立场!
论坛帖子内容仅用于技术交流学习和研究的目的,严禁用于非法目的,否则造成一切后果自负!如帖子内容侵害到你的权益,请联系我们!
防范网络诈骗,远离网络犯罪 违法和不良信息举报电话0663-3422125,QQ: 800073686,邮箱:800073686@b.qq.com
Powered by Discuz! X3.4 揭阳市揭东区精易科技有限公司 ( 粤ICP备12094385号-1) 粤公网安备 44522102000125 增值电信业务经营许可证 粤B2-20192173

快速回复 返回顶部 返回列表