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;

        }

}

 

复制代码

运行结果如下:

 

猜你喜欢

转载自blog.csdn.net/Andrewniu/article/details/83274093