C# 的 Thread (執行緒、線程)

簡介

C# 支援多執行緒 (線程) 的概念,多執行緒在網路程式設計當中具有相當重要的用途,幾乎所有網路程式都會依賴多執行緒去處理對方的連線,在學習網路程式設計之前,讀者有必要先理解多執行續的概念。

程式範例 1

以下程式建立了兩個執行緒 (thread1, thread2),這兩個執行緒都會執行 count 函數,從 0 數到 4。但是在執行結果中,讀者可以發現兩個執行緒是交錯進行的,因此印出的結果是 (0,0,1,1,2,2,3,3,4,4) 這樣的序列,而非 (0,1,2,3,4, 0,1,2,3,4) 這樣的序列,這代表兩個 count() 函數同時都在執行,這就是多執行續的基本功效。

using System;
using System.Threading;
class ThreadTest
{
    public static void Main(String[] args)
    {
        Thread thread1 = new Thread(new ThreadStart(count));
        Thread thread2 = new Thread(new ThreadStart(count));
        thread1.Start();
        thread2.Start();
        thread1.Join();
        thread2.Join();
    }
    public static void count()
    {
        for (int i = 0; i < 5; i++)
        {
         Console.WriteLine(i);
         Thread.Sleep(10);
        }
    }
}
	
D:\myweb\teach\CSharpNetworkProgramming>csc ThreadTest.cs
Microsoft (R) Visual C# 2008 Compiler version 3.5.30729.1
for Microsoft (R) .NET Framework version 3.5
Copyright (C) Microsoft Corporation. All rights reserved.
D:\myweb\teach\CSharpNetworkProgramming>ThreadTest
0
0
1
1
2
2
3
3
4
4
	

程式範例 2

using System;
using System.Threading;
class SimpleThread {
    String name;
    public static void Main(String[] args) {
        SimpleThread a = new SimpleThread("A");
        SimpleThread b = new SimpleThread("B");
        Thread athread = new Thread(new ThreadStart(a.run));
        Thread bthread = new Thread(new ThreadStart(b.run));
        athread.Start();
        bthread.Start();
    }
    SimpleThread(String pName) {
        name = pName;
    }
    public void run() {
        for (int i=0; i<10000; i++) {
         String line = name+":"+i;
         Console.WriteLine(line);
        }
    }
}
	

文章來源:陳鍾誠 (2010年06月10日),(網頁標題) C# 的 Thread (執行緒、線程),(網站標題) 免費電子書:C# 程式設計,2010年06月10日,取自 http://cs0.wikidot.com/thread ,網頁修改第 0 版。


arrow
arrow

    Johnson峰 發表在 痞客邦 留言(0) 人氣()