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();
            }
        }
    }
}
复制代码

 

posted @   txwtech  阅读(1374)  评论(0编辑  收藏  举报
编辑推荐:
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示