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

歡迎訪問 生活随笔!

生活随笔

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

C#

C#中的thread和task之 Thread ThreadPool

發布時間:2023/12/15 C# 46 豆豆
生活随笔 收集整理的這篇文章主要介紹了 C#中的thread和task之 Thread ThreadPool 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

簡介

在.NET Framework/C#中,要提高系統的運行性能,可用使用Thread和新的Task。

Thread在.NET Framework 1.1中引入,是對Posix的thread的封裝。如果后臺的工作線程需要與用戶界面交互,系統會進行限制,如果您需要運行與用戶界面交互的后臺線程,.NET Framework 2.0 版提供了 BackgroundWorker 組件,該組件可以使用事件與用戶界面線程的跨線程封送進行通信。

Task是在.NET Framework 4中添加進來的。這是新的namespace:System.Threading.Tasks;它強調的是adding parallelism and concurrency to applications。在語法上,和lamda表達式更好地結合。

Thread

多線程MultiThread的技術由來已久。使用也簡單。
實例:

using System; using System.Threading;public class Worker {// This method that will be called when the thread is startedpublic void WorkProcess(){while (true){Console.WriteLine("Worker.WorkProcess is running in its own thread.");Thread.Sleep(500);}} };public class ThreadSimple {public static int Main(){Console.WriteLine("Thread Start/Stop/Join Sample");Worker oWorker = new Worker();// Create the thread object, passing in the Worker.WorkProcess method// via a ThreadStart delegate. This does not start the thread.Thread oThread = new Thread(new ThreadStart(oWorker.WorkProcess));// Start the threadoThread.Start();// Spin for a while waiting for the started thread to become// alive:while (!oThread.IsAlive);// Put the Main thread to sleep for 1 millisecond to allow oThread// to do some work:Thread.Sleep(1);// Request that oThread be stoppedoThread.Abort();// Wait until oThread finishes. oThread.Join();Console.WriteLine();Console.WriteLine("Worker.WorkProcess has done");try {Console.WriteLine("Try to restart the Worker.WorkProcess thread");oThread.Start();}catch (ThreadStateException) {Console.Write("ThreadStateException trying to restart Worker.WorkProcess. ");Console.WriteLine("Expected since aborted threads cannot be restarted.");}return 0;} }

ThreadPool

MS介紹說,如果在應用程序中,線程把大部分的時間花費在等待狀態,等待某個事件發生,然后才能給予響應這一般使用ThreadPool(線程池)來解決;而且使用Timer時,線程平時都處于休眠狀態,只是周期性地被喚醒執行;實際在Timer內部也使用的是ThreadPool。

Note: ThreadPool是static類。

簡單的MS示例:

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading;namespace ThreadPoolSimple {class Program{public static void Main(){ThreadPool.SetMaxThreads(1000, 30);for (int i = 0; i < 5; i++){Worker t = new Worker();ThreadPool.QueueUserWorkItem(new WaitCallback(t.ThreadProc), i);}Console.WriteLine("Main thread begin sleep");Thread.Sleep(100000);Console.WriteLine("finish");}public class Worker{public void ThreadProc(object i){Console.WriteLine("Thread[" + i.ToString() + "]");Thread.Sleep(1000);}}} }

但是,線程池的啟動和終止不是我們程序所能控制的。而且線程池中的線程執行完之后是沒有返回值的.

注意: 如果是需要馬上被執行的任務操作,不適合使用ThreadPool,直接使用Thread并調用Start,讓系統開始調度執行。

如果需要在線程間同步,可用使用同步的一下對象,如Mutex、ManualResetEvent等;

lock

在多線程中,如果對某資源的訪問需要同步,則可用使用C#的lock關鍵字,對一個對象變量進行鎖操作。這極大地簡化了對資源鎖定的操作,是一個很好的語法糖果。

來自MS的示例:

using System; using System.Threading;public class Example {static Object obj = new Object();public static void Main(){ThreadPool.QueueUserWorkItem(ShowThreadInformation);var th1 = new Thread(ShowThreadInformation);th1.Start();var th2 = new Thread(ShowThreadInformation);th2.IsBackground = true;th2.Start();Thread.Sleep(500);ShowThreadInformation(null); }private static void ShowThreadInformation(Object state){lock (obj) {var th = Thread.CurrentThread;Console.WriteLine("Managed thread #{0}: ", th.ManagedThreadId);Console.WriteLine(" Background thread: {0}", th.IsBackground);Console.WriteLine(" Thread pool thread: {0}", th.IsThreadPoolThread);Console.WriteLine(" Priority: {0}", th.Priority);Console.WriteLine(" Culture: {0}", th.CurrentCulture.Name);Console.WriteLine(" UI culture: {0}", th.CurrentUICulture.Name);Console.WriteLine();} } }

總結

以上是生活随笔為你收集整理的C#中的thread和task之 Thread ThreadPool的全部內容,希望文章能夠幫你解決所遇到的問題。

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