日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > C# >内容正文

C#

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

發布時間:2023/12/10 C# 26 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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();}}}

運行結果如下:

?

轉載于:https://www.cnblogs.com/DonetRen/p/10177339.html

總結

以上是生活随笔為你收集整理的C#中控制线程池的执行顺序的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。