精易论坛

标题: 大北c#第二课 用信号量控制线程数 [打印本页]

作者: 陌小北    时间: 2017-4-3 11:26
标题: 大北c#第二课 用信号量控制线程数
假如我们有500个帐号需要登录 这时候 如果一次登录肯定会被拦截 我们一次登录5个帐号 c#实现
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading;
  6. using System.Threading.Tasks;

  7. namespace 多线程_队列应用
  8. {
  9. class Program
  10. {
  11. static Queue<string> m_que = new Queue<string>();
  12. static Semaphore m_sem=new Semaphore(5,5);
  13. static void Main(string[] args)
  14. {
  15. int length = 500;
  16. string sname = "";
  17. for (int i = 0; i < length; i++)//先添加50个帐号数据
  18. {
  19. sname = "user_" + i.ToString();
  20. m_que.Enqueue(sname);
  21. }

  22. Thread th_wo = new Thread(work);
  23. th_wo.Start();


  24. Console.ReadKey();
  25. }


  26. static void work()
  27. {
  28. while(m_que.Count>0)
  29. {
  30. m_sem.WaitOne();
  31. var th = new Thread(new ThreadStart(()=>test_que(m_que.Dequeue())));
  32. th.Start();
  33. }
  34. <P> </P>
  35. }

  36. static void test_que(string p_name)
  37. {
  38. Console.WriteLine(p_name);

  39. Thread.Sleep(5000);

  40. m_sem.Release();
  41. }

  42. }
  43. }
复制代码



作者: 进击    时间: 2017-4-3 11:32
有没有系统的教程来学习?
作者: 陌小北    时间: 2017-4-3 11:36
我也是瞎看一些教程 然后自己看代码 推荐泰课在线 搜c#教程 里面讲的不错!
作者: pan1339    时间: 2017-6-7 21:38


学习学习
作者: 夜鬼    时间: 2019-4-18 22:53
新技能 已get
作者: 夜鬼    时间: 2019-4-19 12:18
winform listView  可以这样实现不
作者: yuzhong    时间: 2024-10-7 09:53
11111111111111111111111111




欢迎光临 精易论坛 (https://125.confly.eu.org/) Powered by Discuz! X3.4