Computer >> Máy Tính >  >> Lập trình >> C#

Chương trình C # để tạo một nhóm chủ đề


Đối với nhóm luồng, hãy tạo nhiều hơn hai hàm và phương thức hàng đợi để thực thi.

Trước tiên, hãy tạo một phương thức như -

public void one(object o) {
   for (int i = 0; i <= 3; i++) {
      Console.WriteLine("One executed");
   }
}

Theo cách tương tự, hãy tạo nhiều phương thức hơn và sau đó sử dụng ThreadPool.QueueUserWorkItem để xếp hàng đợi các phương thức thực thi -

Demo d = new Demo();
for (int i = 0; i < 3; i++) {
   ThreadPool.QueueUserWorkItem(new WaitCallback(d.one));
   ThreadPool.QueueUserWorkItem(new WaitCallback(d.two));
   ThreadPool.QueueUserWorkItem(new WaitCallback(d.three));
}

Ví dụ

Bạn có thể thử chạy mã C # sau để tạo Nhóm chủ đề.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
class Demo {
   public void one(object o) {
      for (int i = 0; i <= 3; i++) {
         Console.WriteLine("One executed");
      }
   }
   public void two(object o) {
      for (int i = 0; i <= 3; i++) {
         Console.WriteLine("Two executed");
      }
   }
   public void three(object o) {
      for (int i = 0; i <= 3; i++) {
         Console.WriteLine("Three executed");
      }
   }
   static void Main() {
      Demo d = new Demo();
      for (int i = 0; i < 3; i++) {
         ThreadPool.QueueUserWorkItem(new WaitCallback(d.one));
         ThreadPool.QueueUserWorkItem(new WaitCallback(d.two));
         ThreadPool.QueueUserWorkItem(new WaitCallback(d.three));
      }
      Console.Read();
   }
}

Đầu ra

Two executed
Two executed
Two executed
Two executed
Two executed
Two executed
Two executed
One executed
One executed
One executed
One executed
One executed
Two executed
Two executed
Three executed
Three executed
Two executed
One executed
Three executed
Two executed
Three executed
One executed
One executed
One executed