C#中控制线程池的执行顺序

在使用线程池时,当用线程池执行多个任务时,由于执行的任务时间过长,会导制两个任务互相执行,如果两个任务具有一定的操作顺序,可能会导制不同的操作结果,这时,就要将线程池按顺序操作。下面先给一段代码,该代码是不按顺序对线程池进行操作的,代码如下:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading;

namespace ConsoleApplication1

{

    class Program

    {

        static void Main(string[] args)

        {

            AutoResetEvent autoEvent = new AutoResetEvent(false);

            ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadMethod), autoEvent);

            ThreadPool.QueueUserWorkItem(new WaitCallback(WorkMethod), autoEvent);

            Console.ReadLine();

        }

        static void ThreadMethod(object stateInfo)

        {

            for (int i = 0; i < 100;i++ )

                Console.WriteLine("ThreadOne, executing ThreadMethod, " + "is {0}from the thread pool.", Thread.CurrentThread.IsThreadPoolThread ? "" : "not ");

        }

        static void WorkMethod(object stateInfo)

        {

            for (int i = 0; i < 100; i++)

                Console.WriteLine("ThreadTwo, executing WorkMethod");

        }

    }

}

运行结果如图1、图2所示。

 

图1  运行结果的上半部

 

图2  运行结果的下半部

从图1、图2可以看出,在使用线程池对线程进行操作时,由于各任务的时间过长,多个任务的线程可能会交互操作,那么,如何才能将线程池按指定的顺序进行操作呢?主要是用AutoResetEvent类来实现的。

可以用AutoResetEvent类的WaitOne方法阻止线程,然后只执行当前操作的线程池,当遇到AutoResetEvent类的Set方法后,将当前线程设置为终止状态,执行其他等待的线程。修改后的代码如下:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading;

namespace ConsoleApplication1

{

    class Program

    {

        static void Main(string[] args)

        {

            AutoResetEvent autoEvent = new AutoResetEvent(false);

            ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadMethod), autoEvent);

            autoEvent.WaitOne();

            ThreadPool.QueueUserWorkItem(new WaitCallback(WorkMethod), autoEvent);

            autoEvent.WaitOne();

            Console.ReadLine();

        } 

        static void ThreadMethod(object stateInfo)
        {

            for (int i = 0; i < 100;i++ )

                Console.WriteLine("ThreadOne, executing ThreadMethod, " + "is {0}from the thread pool.", Thread.CurrentThread.IsThreadPoolThread ? "" : "not ");

            ((AutoResetEvent)stateInfo).Set();

        }
 
        static void WorkMethod(object stateInfo)

        {

            for (int i = 0; i < 100; i++)

                Console.WriteLine("ThreadTwo, executing WorkMethod");

            ((AutoResetEvent)stateInfo).Set();

        }

    }

}

运行结果如下:

 

猜你喜欢

转载自www.cnblogs.com/DonetRen/p/10177339.html