c# 指定線程數的多線程操作

來源:互聯網
上載者:User

標籤:tco   remove   建議   false   線程   waiting   cal   eth   round   

多線程操作一直用ThreadPool.QueueUserWorkItem比較多,今天想到用這個方式實現,控制並發線程的數量。

主要思路是:

  1.聲明開啟的線程數 int threadCount = 2;

  2.建立一個泛型集合List<TaskInfo>  workingList = new List<TaskInfo>(); 需要開啟多少個線程,就從Queue裡取幾個taskInfo,添加到workingList,同時,把TaskInfo.IsBusy置為true.

  3.在子線程中,執行完成時,再把TaskInfo.IsBusy置為false.

  4.在主線程中,迴圈往workingList中放入TaskInfo 對象, 並通過判斷TaskInfo.isBusy, 移除執行完成的TaskInfo對象。

代碼如下,如有任何建議,還望不吝賜教。

public class TaskInfo{    public bool IsBusy { get; set; }    public int ID { get; set; }}public class Test{             public void Work(object obj)    {        var taskInfo = obj as TaskInfo;
     //Do something ... Thread.Sleep(5000); taskInfo.IsBusy = false; } public void Test_MultyThread() { int threadCount = 2; Queue<TaskInfo> taskQueue = new Queue<TaskInfo>(); taskQueue.Enqueue(new TaskInfo() { ID = 1 }); taskQueue.Enqueue(new TaskInfo() { ID = 2 }); taskQueue.Enqueue(new TaskInfo() { ID = 3 }); taskQueue.Enqueue(new TaskInfo() { ID = 4 }); taskQueue.Enqueue(new TaskInfo() { ID = 5 }); List<TaskInfo> workingList = new List<TaskInfo>(); while (taskQueue.Count > 0) { if (workingList.Count < threadCount) { var taskInfo = taskQueue.Dequeue(); taskInfo.IsBusy = true; workingList.Add(taskInfo); Console.WriteLine("Processing ID: {0}", taskInfo.ID); ThreadPool.QueueUserWorkItem(new WaitCallback(Work), taskInfo); } else { if (workingList.Any(x => !x.IsBusy)) { workingList.RemoveAll(x => !x.IsBusy); } else { Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("==> Waiting for free thread ..."); Console.ResetColor(); Thread.Sleep(1000); } } } }}

 

c# 指定線程數的多線程操作

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.