C#執行緒範例


在執行執行緒時可以呼叫靜態和非靜態方法。要呼叫靜態和非靜態方法,需要在ThreadStart類別建構函式中傳遞方法名稱。對於靜態方法,不需要建立類的範例。可以通過類的名稱來參照它。

using System;
using System.Threading;
public class MyThread
{
    public static void Thread1()
    {
        for (int i = 0; i < 10; i++)
        {
            Console.WriteLine("Thread1: "+i);
        }
    }
}
public class ThreadExample
{
    public static void Main()
    {
        Thread t1 = new Thread(new ThreadStart(MyThread.Thread1));
        Thread t2 = new Thread(new ThreadStart(MyThread.Thread1));
        t1.Start();
        t2.Start();
    }
}

上述程式的輸出可以是任何東西,因為執行緒之間有上下文切換。在我執行上面範例時輸出以下結果 -

Thread1: 0
Thread1: 1
Thread1: 0
Thread1: 1
Thread1: 2
Thread1: 3
Thread1: 4
Thread1: 5
Thread1: 6
Thread1: 7
Thread1: 8
Thread1: 2
Thread1: 3
Thread1: 4
Thread1: 5
Thread1: 6
Thread1: 7
Thread1: 8
Thread1: 9
Thread1: 9

C# 執行緒範例:非靜態方法

對於非靜態方法,需要建立類的範例,以便我們可以在ThreadStart類別建構函式中參照它。

using System;
using System.Threading;

public class MyThread
{
    private String name;

    public MyThread(String name)
    {
        this.name = name;
    }
    public void Thread1()
    {
        for (int i = 0; i < 10; i++)
        {
            Console.WriteLine(this.name+": "+i);
        }
    }
}

public class ThreadExample
{
    public static void Main()
    {
        MyThread mt = new MyThread("Thread1");
        MyThread mt2 = new MyThread("Thread2");
        Thread t1 = new Thread(new ThreadStart(mt.Thread1));
        Thread t2 = new Thread(new ThreadStart(mt2.Thread1));
        t1.Start();
        t2.Start();
    }
}

這個程式的輸出可以是任何順序,因為執行緒之間有上下文切換,所以每次執行的結果都不太一樣。輸出結果如下所示 -

Thread1: 0
Thread1: 1
Thread2: 0
Thread2: 1
Thread2: 2
Thread2: 3
Thread2: 4
Thread2: 5
Thread2: 6
Thread2: 7
Thread2: 8
Thread2: 9
Thread1: 2
Thread1: 3
Thread1: 4
Thread1: 5
Thread1: 6
Thread1: 7
Thread1: 8
Thread1: 9

C# 執行緒範例:在每個執行緒上執行不同的任務

下面讓我們來看看另外一個例子,在每個執行緒上執行不同的方法。

using System;
using System.Threading;

public class MyThread
{
    public static void method1()
    {
        for (int i = 0; i < 5; i++)
        {
            Console.WriteLine("This is method1 :" + i);
        }
    }
    public static void method2()
    {
        for (int i = 0; i < 5; i++)
        {
            Console.WriteLine("This is method2 :"+i);
        }

    }
}
public class ThreadExample
{
    public static void Main()
    {
        Thread t1 = new Thread(new ThreadStart(MyThread.method1));
        Thread t2 = new Thread(new ThreadStart(MyThread.method2));
        t1.Start();
        t2.Start();
    }
}

這個程式的輸出可以是任何順序,因為執行緒之間有上下文切換,所以每次執行的結果都不太一樣。輸出結果如下所示 -

This is method1 :0
This is method1 :1
This is method2 :0
This is method2 :1
This is method2 :2
This is method2 :3
This is method2 :4
This is method1 :2
This is method1 :3
This is method1 :4