C#往線程裡傳遞參數的方法小結_C#教程

來源:互聯網
上載者:User

傳參方式有兩種:

1、建立帶參構造方法類 傳參

2、利用Thread.start(8)直接傳參,該方法會接收一個對象,並將該對象傳遞給線程,因此線上程中啟動的方法

必須接收object類型的單個參數。

Thread (ParameterizedThreadStart) 初始化 Thread 類的新執行個體,指定允許對象線上程啟動時傳遞給線程的委託。

Thread (ThreadStart) 初始化 Thread 類的新執行個體。

由 .NET Compact Framework 支援。

Thread (ParameterizedThreadStart, Int32) 初始化 Thread 類的新執行個體,指定允許對象線上程啟動時傳遞給線程的委託,並指定線程的最大堆棧大小。

Thread (ThreadStart, Int32) 初始化 Thread 類的新執行個體,指定線程的最大堆棧大小。

由 .NET Compact Framework 支援。

我們如果定義不帶參數的線程,可以用ThreadStart,帶一個參數的用ParameterizedThreadStart。帶多個參數的用另外的方法,下面逐一講述。

一、不帶參數的

using System; using System.Collections.Generic; using System.Text; using System.Threading; namespace AAAAAA { class AAA { public static void Main() { Thread t = new Thread(new ThreadStart(A)); t.Start(); Console.Read(); } private static void A() { Console.WriteLine("Method A!"); } } } 

結果顯示Method A!

二、帶一個參數的

由於ParameterizedThreadStart要求參數類型必須為object,所以定義的方法B形參類型必須為object。

using System; using System.Collections.Generic; using System.Text; using System.Threading; namespace AAAAAA { class AAA { public static void Main() { Thread t = new Thread(new ParameterizedThreadStart(B)); t.Start("B"); Console.Read(); } private static void B(object obj) { Console.WriteLine("Method {0}!",obj.ToString ()); } } } 

結果顯示Method B!

三、帶多個參數的

由於Thread預設只提供了這兩種建構函式,如果需要傳遞多個參數,我們可以自己將參數作為類的屬性。定義類的對象時候執行個體化這個屬性,然後進行操作。

using System; using System.Collections.Generic; using System.Text; using System.Threading; namespace AAAAAA { class AAA { public static void Main() { My m = new My(); m.x = 2; m.y = 3; Thread t = new Thread(new ThreadStart(m.C)); t.Start(); Console.Read(); } } class My { public int x, y; public void C() { Console.WriteLine("x={0},y={1}", this.x, this.y); } } } 

結果顯示x=2,y=3

四、利用結構體給參數傳值。

定義公用的public struct,裡面可以定義自己需要的參數,然後在需要添加線程的時候,可以定義結構體的執行個體。

//結構體 struct RowCol { public int row; public int col; }; //定義方法 public void Output(Object rc) { RowCol rowCol = (RowCol)rc; for (int i = 0; i < rowCol.row; i++) { for (int j = 0; j < rowCol.col; j++) Console.Write("{0} ", _char); Console.Write("\n"); } } 

以上所述是小編給大家介紹的C#往線程裡傳遞參數的方法小結,希望對大家有所協助,如果大家有任何疑問請給我留言,小編會及時回複大家的。在此也非常感謝大家對雲棲社區網站的支援!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.