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;
    
            }
    
    }
    
     

    运行结果如下:

     

  • 相关阅读:
    MySQL5.6 community从下载到安装
    SVN使用
    VIsualSVN server 安装及旧仓库导入
    在VisualSVN创建新的Repository
    MFC用PostMessage传递消息
    Postgresql命令行和数据库备份与恢复
    makefile复习时发现的编写makefile规则注意事项
    js IDE WebStorm 注册码
    mysql学习笔记之基础篇
    c++继承详解
  • 原文地址:https://www.cnblogs.com/jlw123199/p/6812931.html
Copyright © 2011-2022 走看看