C#中控制线程池的执行顺序 autoEvent.WaitOne();

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

不按顺序对线程池进行操作,代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace c_sharp_thread_pool_test
{
    class Program
    {
        static void Main(string[] args)
        {
            AutoResetEvent autoEvent = new AutoResetEvent(false);
            ThreadPool.QueueUserWorkItem(new WaitCallback(thread_method),autoEvent);
            ThreadPool.QueueUserWorkItem(new WaitCallback(work_method),autoEvent);
            Console.ReadLine();
        }

        static void thread_method(object stateInfo)
        {
            for (int i = 0; i < 10; i++)
                Console.WriteLine("i={0}_thread_method:{1}",i,Thread.CurrentThread.IsThreadPoolThread?"":"not");
        }
        static void work_method(object stateInfo)
        {
            for(int i=0;i<10;i++)
            {
                Console.WriteLine("work_method,i={0}",i);
            }
        }
    }
}

//

用AutoResetEvent类来实现的顺序执行

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

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace c_sharp_thread_pool_test
{
    class Program
    {
        static void Main(string[] args)
        {
            AutoResetEvent autoEvent = new AutoResetEvent(false);
            ThreadPool.QueueUserWorkItem(new WaitCallback(thread_method),autoEvent);

            //
            autoEvent.WaitOne();
            ThreadPool.QueueUserWorkItem(new WaitCallback(work_method),autoEvent);
            //
            autoEvent.WaitOne();
            Console.ReadLine();
        }

        static void thread_method(object stateInfo)
        {
            for (int i = 0; i < 10; i++)
                Console.WriteLine("i={0}_thread_method:{1}",i,Thread.CurrentThread.IsThreadPoolThread?"":"not");
            //
            ((AutoResetEvent)stateInfo).Set();
        }
        static void work_method(object stateInfo)
        {
            for(int i=0;i<10;i++)
            {
                Console.WriteLine("work_method,i={0}",i);
                //
                ((AutoResetEvent)stateInfo).Set();
            }
        }
    }
}

欢迎讨论,相互学习。 txwtech@163.com
原文地址:https://www.cnblogs.com/txwtech/p/14857399.html