C#線程命名實例

使用Thread類的Name屬性來更改或獲取線程的名稱。下面我們來看一個例子,演示如何設置和獲取線程的名稱。

using System;
using System.Threading;

public class MyThread
{
    public void Thread1()
    {
        for(int i=0; i<5; i++)
        {
            Thread t = Thread.CurrentThread;
            Console.WriteLine(t.Name + " is running at :"+i);
        }
    }
}
public class ThreadExample
{
    public static void Main()
    {
        MyThread mt = new MyThread();
        Thread t1 = new Thread(new ThreadStart(mt.Thread1));
        Thread t2 = new Thread(new ThreadStart(mt.Thread1));
        Thread t3 = new Thread(new ThreadStart(mt.Thread1));
        t1.Name = "Thread1";
        t2.Name = "Thread2";
        t3.Name = "Thread3";
        t1.Start();
        t2.Start();
        t3.Start();
    }
}

執行上面示例代碼,得到以下結果 -

Thread1 is running at :0
Thread2 is running at :0
Thread3 is running at :0
Thread3 is running at :1
Thread3 is running at :2
Thread3 is running at :3
Thread3 is running at :4
Thread2 is running at :1
Thread2 is running at :2
Thread2 is running at :3
Thread2 is running at :4
Thread1 is running at :1
Thread1 is running at :2
Thread1 is running at :3
Thread1 is running at :4