c#使用多線程的幾種方式樣本詳解

來源:互聯網
上載者:User
(1)不需要傳遞參數,也不需要返回參數

ThreadStart是一個委託,這個委託的定義為void ThreadStart(),沒有參數與傳回值。

class Program{static void Main(string[] args){for (int i = 0; i < 30; i++){ThreadStart threadStart = new ThreadStart(Calculate);Thread thread = new Thread(threadStart);thread.Start();}Thread.Sleep(2000);Console.Read();}public static void Calculate(){DateTime time = DateTime.Now;//得到目前時間Random ra = new Random();//隨機數對象Thread.Sleep(ra.Next(10,100));//隨機休眠一段時間Console.WriteLine(time.Minute + ":" + time.Millisecond);}}

(2)需要傳遞單個參數

ParameterThreadStart委託定義為void ParameterizedThreadStart(object state),有一個參數但是沒有傳回值。

class Program{static void Main(string[] args){for (int i = 0; i < 30; i++){ParameterizedThreadStart tStart = new ParameterizedThreadStart(Calculate);Thread thread = new Thread(tStart);thread.Start(i*10+10);//傳遞參數}Thread.Sleep(2000);Console.Read();}public static void Calculate(object arg){Random ra = new Random();//隨機數對象Thread.Sleep(ra.Next(10, 100));//隨機休眠一段時間Console.WriteLine(arg);}}

(3)使用專門的線程類(常用)

使用線程類可以有多個參數與多個傳回值,十分靈活!

class Program{static void Main(string[] args){MyThread mt = new MyThread(100);ThreadStart threadStart = new ThreadStart(mt.Calculate);Thread thread = new Thread(threadStart);thread.Start();   //等待線程結束while (thread.ThreadState != ThreadState.Stopped){Thread.Sleep(10);}Console.WriteLine(mt.Result);//列印傳回值Console.Read();}}public class MyThread//線程類{public int Parame { set; get; }//參數public int Result { set; get; }//傳回值//建構函式public MyThread(int parame){this.Parame = parame;}//線程執行方法public void Calculate(){Random ra = new Random();//隨機數對象Thread.Sleep(ra.Next(10, 100));//隨機休眠一段時間Console.WriteLine(this.Parame);this.Result = this.Parame * ra.Next(10, 100);}}

(4)使用匿名方法(常用)

使用匿名方法啟動線程可以有多個參數和傳回值,而且使用非常方便!

class Program{static void Main(string[] args){int Parame = 100;//當做參數int Result = 0;//當做傳回值//匿名方法ThreadStart threadStart = new ThreadStart(delegate(){Random ra = new Random();//隨機數對象Thread.Sleep(ra.Next(10, 100));//隨機休眠一段時間Console.WriteLine(Parame);//輸出參數Result = Parame * ra.Next(10, 100);//計算傳回值});Thread thread = new Thread(threadStart);thread.Start();//多線程啟動匿名方法//等待線程結束while (thread.ThreadState != ThreadState.Stopped){Thread.Sleep(10);}Console.WriteLine(Result);//列印傳回值Console.Read();}}

(5)使用委託開啟多線程(多線程深入)

1、用委託(Delegate)的BeginInvoke和EndInvoke方法操作線程

BeginInvoke方法可以使用線程非同步地執行委託所指向的方法。然後通過EndInvoke方法獲得方法的傳回值(EndInvoke方法的傳回值就是被呼叫者法的傳回值),或是確定方法已經被成功調用。

class Program{private delegate int NewTaskDelegate(int ms);private static int newTask(int ms){Console.WriteLine("任務開始");Thread.Sleep(ms);Random random = new Random();int n = random.Next(10000);Console.WriteLine("任務完成");return n;}static void Main(string[] args){NewTaskDelegate task = newTask;IAsyncResult asyncResult = task.BeginInvoke(2000, null, null);//EndInvoke方法將被阻塞2秒int result = task.EndInvoke(asyncResult);Console.WriteLine(result);Console.Read();}}

2、使用IAsyncResult.IsCompleted屬性來判斷非同步呼叫是否完成

class Program{private delegate int NewTaskDelegate(int ms);private static int newTask(int ms){Console.WriteLine("任務開始");Thread.Sleep(ms);Random random = new Random();int n = random.Next(10000);Console.WriteLine("任務完成");return n;}static void Main(string[] args){NewTaskDelegate task = newTask;IAsyncResult asyncResult = task.BeginInvoke(2000, null, null);//等待非同步執行完成while (!asyncResult.IsCompleted){Console.Write("*");Thread.Sleep(100);}// 由於非同步呼叫已經完成,因此, EndInvoke會立刻返回結果int result = task.EndInvoke(asyncResult);Console.WriteLine(result);Console.Read();}}

3、使用WaitOne方法等待非同步方法呼叫執行完成

WaitOne的第一個參數表示要等待的毫秒數,在指定時間之內,WaitOne方法將一直等待,直到非同步呼叫完成,並發出通知,WaitOne方法才返回true。當等待指定時間之後,非同步呼叫仍未完成,WaitOne方法返回false,如果指定時間為0,表示不等待,如果為-1,表示永遠等待,直到非同步呼叫完成。

class Program{private delegate int NewTaskDelegate(int ms);private static int newTask(int ms){Console.WriteLine("任務開始");Thread.Sleep(ms);Random random = new Random();int n = random.Next(10000);Console.WriteLine("任務完成");return n;}static void Main(string[] args){NewTaskDelegate task = newTask;IAsyncResult asyncResult = task.BeginInvoke(2000, null, null);//等待非同步執行完成while (!asyncResult.AsyncWaitHandle.WaitOne(100, false)){Console.Write("*");}int result = task.EndInvoke(asyncResult);Console.WriteLine(result);Console.Read();}}

4、使用回調方式返回結果

要注意的是“my.BeginInvoke(3,300, MethodCompleted, my)”,BeginInvoke方法的參數傳遞方式:

前面一部分(3,300)是其委託本身的參數。

倒數第二個參數(MethodCompleted)是回調方法委託類型,他是回調方法的委託,此委託沒有傳回值,有一個IAsyncResult類型的參數,當method方法執行完後,系統會自動調用MethodCompleted方法。

最後一個參數(my)需要向MethodCompleted方法中傳遞一些值,一般可以傳遞被呼叫者法的委託,這個值可以使用IAsyncResult.AsyncState屬性獲得。

class Program{private delegate int MyMethod(int second, int millisecond);//線程執行方法private static int method(int second, int millisecond){Console.WriteLine("線程休眠" + (second * 1000 + millisecond) + "毫秒");Thread.Sleep(second * 1000 + millisecond);Random random = new Random();return random.Next(10000);}//回調方法private static void MethodCompleted(IAsyncResult asyncResult){if (asyncResult == null || asyncResult.AsyncState == null){Console.WriteLine("回調失敗!!!");return;}int result = (asyncResult.AsyncState as MyMethod).EndInvoke(asyncResult);Console.WriteLine("任務完成,結果:" + result);}static void Main(string[] args){MyMethod my = method;IAsyncResult asyncResult = my.BeginInvoke(3,300, MethodCompleted, my);Console.WriteLine("任務開始");Console.Read();}}

5、其他組件的BeginXXX和EndXXX方法

在其他的.net組件中也有類似BeginInvoke和EndInvoke的方法,如System.Net.HttpWebRequest類的BeginGetResponse和EndGetResponse方法。其使用方法類似於委託類型的BeginInvoke和EndInvoke方法,例如:

class Program{//回呼函數private static void requestCompleted(IAsyncResult asyncResult){if (asyncResult == null || asyncResult.AsyncState==null){Console.WriteLine("回調失敗");return;}HttpWebRequest hwr = asyncResult.AsyncState as HttpWebRequest;HttpWebResponse response = (HttpWebResponse)hwr.EndGetResponse(asyncResult);StreamReader sr = new StreamReader(response.GetResponseStream());string str = sr.ReadToEnd();Console.WriteLine("返迴流長度:"+str.Length);}static void Main(string[] args){HttpWebRequest request =(HttpWebRequest)WebRequest.Create("http://www.baidu.com");//非同步請求IAsyncResult asyncResult = request.BeginGetResponse(requestCompleted, request);Console.WriteLine("任務開始");Console.Read();}}
  • 相關文章

    聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.