zoukankan      html  css  js  c++  java
  • C#多线程顺序依赖执行控制

    在开发过程中,经常需要多个任务并行的执行的场景,同时任务之间又需要先后依赖的关系。针对这样的处理逻辑,通常会采用多线程的程序模型来实现。

    比如A、B、C三个线程,A和B需要同时启动,并行处理,且B需要依赖A完成,在进行后续的处理,C需要B完成后开始处理。

    针对这个场景,使用了ThreadPool,ManualResetEvent等.net框架内置的类功能进行了模拟,实现代码如下:

    public class MultipleThreadCooperationSample
    
        {
    
            public static ManualResetEvent eventAB = new ManualResetEvent(false);
    
     
    
            public static ManualResetEvent eventBC = new ManualResetEvent(false);
    
     
    
            public static int Main(string[] args)
    
            {
    
                //so called thread A
    
                ThreadPool.QueueUserWorkItem(new WaitCallback(d =>
    
                {
    
                    Console.WriteLine("Start A thread");
    
                    Thread.Sleep(4000);
    
                    eventAB.Set();
    
                }));
    
     
    
                //thread A
    
                ThreadPool.QueueUserWorkItem(new WaitCallback(d =>
    
                {
    
                    Console.WriteLine("Start B thread and wait A thread to finised.");
    
                    eventAB.WaitOne();
    
                   
    
                    Console.WriteLine("Process something within B thread");
    
     
    
                    Thread.Sleep(4000);
    
                    eventBC.Set();
    
                }));
    
     
    
     
    
                eventBC.WaitOne(Timeout.Infinite, true);
    
                //thread C
    
                ThreadPool.QueueUserWorkItem(new WaitCallback(d =>
    
                {
    
                    Console.WriteLine("From C thread, everything is done.");
    
                }));
    
     
    
                Console.ReadLine();
    
     
    
                return 0;
    
            }
    
    }
    
     

    运行结果如下:

     

  • 相关阅读:
    jquery学会的
    oracle技巧-持续更新
    c语言技巧--长期更新
    2019暑假集训 最大子树和
    2019暑假集训 细胞分裂
    2019暑假集训 金明的预算方案
    2019暑假集训 能量项链
    2019暑假集训 神经网络
    0023-特殊的方程
    0022-并联电阻
  • 原文地址:https://www.cnblogs.com/jlw123199/p/6812931.html
Copyright © 2011-2022 走看看