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;

        }

}

 

 

运行结果如下:

 

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM