C# 多线程与高并发处理并且具备暂停、继续、停止功能

复制代码
--近期有一个需要运用多线程的项目,会有并发概率,所以写了一份代码,可能有写地方还不完善,后续有需求在改
1 /// <summary> 2 /// 并发对象 3 /// </summary> 4 public class MeterAsyncQueue 5 { 6 public MeterAsyncQueue() 7 { 8 MeterInfoTask = new MeterInfo(); 9 } 10 11 public MeterInfo MeterInfoTask { get; set; } 12 } 13 public class MeterInfo 14 { 15 public MeterInfo() 16 { 17 18 } 19 public int Id { get; set; } 20 21 }
复制代码
复制代码
  1     /// <summary>
  2     /// 线程通用类  3 /// </summary>  4 public class TaskCommand  5  {  6 CancellationTokenSource tokenSource = new CancellationTokenSource();  7 ManualResetEvent resetEvent = new ManualResetEvent(true);  8 Thread thread = null;  9 /// <summary>  10 /// 开始任务  11 /// </summary>  12 public void StartData()  13  {  14 tokenSource = new CancellationTokenSource();  15 resetEvent = new ManualResetEvent(true);  16  17 List<int> Ids = new List<int>();  18 for (int i = 0; i < 10000; i++)  19  {  20  Ids.Add(i);  21  }  22 thread = new Thread(new ThreadStart(() => StartTask(Ids)));  23  thread.Start();  24  }  25 /// <summary>  26 /// 暂停任务  27 /// </summary>  28 public void OutData()  29  {  30 //task暂停  31  resetEvent.Reset();  32  }  33 /// <summary>  34 /// 继续任务  35 /// </summary>  36 public void ContinueData()  37  {  38 //task继续  39  resetEvent.Set();  40  }  41 /// <summary>  42 /// 取消任务  43 /// </summary>  44 public void Cancel()  45  {  46 //释放对象  47  resetEvent.Dispose();  48 foreach (var CurrentTask in ParallelTasks)  49  {  50 if (CurrentTask != null)  51  {  52 if (CurrentTask.Status == TaskStatus.Running) { }  53  {  54 //终止task线程  55  tokenSource.Cancel();  56  }  57  }  58  }  59  thread.Abort();  60  }  61 /// <summary>  62 /// 执行数据  63 /// </summary>  64 /// <param name="Index"></param>  65 public void Execute(int Index)  66  {  67 //阻止当前线程  68  resetEvent.WaitOne();  69  70 Console.WriteLine("当前第" + Index + "个线程");  71  72 Thread.Sleep(1000);  73  74  }  75 //队列对象  76 private Queue<MeterAsyncQueue> AsyncQueues { get; set; }  77  78 /// <summary>  79 /// 并发任务数  80 /// </summary>  81 private int ParallelTaskCount { get; set; }  82  83  84 /// <summary>  85 /// 并行任务集合  86 

转载于:https://www.cnblogs.com/mengcheng9300/p/11613232.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值