c#和.net基類為開發多線程應用程式提供了強大的支援。下面是我看書和結合網上的一些資源整理出來的筆記。因為線程相關的知識比較繁雜和高深(並且本人開發經驗欠缺),所以寫的很淺顯甚至幼稚,理解不妥之處在所難免。
1.怎樣建立一個線程(常用的建立方式)
Code
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
namespace ThreadStudy
{
public class MyThreadClass
{
public static void ThreadTest()
{
Console.WriteLine("This is a thread test.The worker thread is started!");
}
public static void ThreadTestWithParameter(object stateInfo)
{
Console.WriteLine(string.Format("This is {0}.The worker thread is started!", stateInfo));
}
delegate void ThreadTestDelegate(object objName);
static ThreadTestDelegate myTest = new ThreadTestDelegate(ThreadTestWithParameter);
//線程完成之後回調的函數
public static void TaskFinished(IAsyncResult result)
{
// myTest.EndInvoke(result); //無傳回值
Console.WriteLine("Thread test callback end.");
}
/* 怎樣建立一個線程? */
public static void Main()
{
//1.使用Thread類
/*a、無參數委託*/
ThreadStart ts = new ThreadStart(ThreadTest); //通過ThreadStart委託(無參數)告訴子線程講執行什麼方法
Thread currentThread = new Thread(ts);
currentThread.Name = "my first thread test without parameter"; //給線程起名字,不是必須的
currentThread.Start(); //啟動新線程
currentThread.Abort();
Thread.Sleep(2000);
/*b、帶參數委託*/
ParameterizedThreadStart pts = new ParameterizedThreadStart(ThreadTestWithParameter); //通過ParameterizedThreadStart委託(參數)告訴子線程講執行什麼方法
Thread curThread = new Thread(pts);
curThread.Name = "my first thread test with parameter(s)"; //給線程起名字,不是必須的
curThread.Start("my first thread test with a parameter");//啟動新線程,出入一個參數(也可以多個參數)
curThread.Abort();
Thread.Sleep(2000);
//2.使用ThreadPool類
WaitCallback wcb = new WaitCallback(ThreadTestWithParameter); //通過WaitCallback委託(可以帶參數,也可不帶參數,這裡的執行個體是帶參數的)告訴子線程講執行什麼方法
ThreadPool.QueueUserWorkItem(wcb, "my first threadpool test");
ThreadPool.QueueUserWorkItem(ThreadTestWithParameter, "my second threadpool test");
Thread.Sleep(2000);
//3.使用Delegate.BeginInvoke
myTest.BeginInvoke("my thread test without callback", null, null);//此處開始非同步執行,如果不需要執行什麼後續操作也可以不使用回調
Thread.Sleep(2000);
//適用於需要傳遞參數且需要返回參數
myTest.BeginInvoke("my thread test with call back", new AsyncCallback(TaskFinished), null);//此處開始非同步執行,並且可以給出一個回呼函數
/* 最後擷取當前正在啟動並執行線程的一些資訊 */
Console.WriteLine(Thread.CurrentThread.CurrentCulture.ToString());
Console.WriteLine(Thread.CurrentThread.CurrentUICulture.ToString());
Console.WriteLine(Thread.CurrentThread.ManagedThreadId.ToString());
Console.WriteLine(Thread.CurrentThread.IsThreadPoolThread.ToString());
Console.WriteLine(Thread.CurrentThread.IsAlive.ToString());
Console.WriteLine(Thread.CurrentThread.IsBackground.ToString());
Console.WriteLine(Thread.CurrentThread.Priority.ToString());
Console.Read();
}
}
}
2.線程的優先順序
如果在應用程式中有多個線程在運行,但一些線程比另外的一些線程重要,這時候就要用到線程的優先順序。一般情況下,優先順序高的線程在工作時,就不會給優先順序低的線程分配任何時間片。高優先順序的線程可以完全阻止低優先順序的線程執行,因此在改變線程優先順序的時候要特別小心。
線程的優先順序可以定義為枚舉ThreadPriority,即Highest,AboveNormal,Normal,BelowNormal和Lowest。
Code
using System;
using System.Threading;
class Program
{
static int interval;
static void Main()
{
Console.WriteLine("Please input a number:");
interval = int.Parse(Console.ReadLine());
Thread curThread = Thread.CurrentThread;
curThread.Name = "Main Thread";
ThreadStart ts = new ThreadStart(StartMethod);
Thread workerThread = new Thread(ts);
workerThread.Name = "Worker Thread";
workerThread.Priority = ThreadPriority.AboveNormal; //線程優先順序
workerThread.Start();
DisplayNumbers();
Console.WriteLine("Main Thread Finished!");
Console.ReadLine();
}
static void DisplayNumbers()
{
Thread thisThread = Thread.CurrentThread;
string name = thisThread.Name;
Console.WriteLine("Starting Thread:" + name);
Console.WriteLine(name + ":CurrentCulture=" + thisThread.CurrentCulture);
for (int i = 0; i < 6 * interval; i++)
{
if (i % interval == 0)
{
Console.WriteLine(name + ":count has reached " + i);
}
}
}
static void StartMethod()
{
DisplayNumbers();
Console.WriteLine("Worker Thread Finished!");
}
}
在下一篇會接著介紹關於c#線程的“同步”相關知識。這裡先打住,因為正在看書,還沒消化過來^_^