c#線程間傳遞參數(shù)詳解
線程操作主要用到Thread類,他是定義在System.Threading.dll下。使用時(shí)需要添加這一個(gè)引用。該類提供給我們四個(gè)重載的構(gòu)造函數(shù)(以下引自msdn)。
Thread (ParameterizedThreadStart) 初始化 Thread 類的新實(shí)例,指定允許對(duì)象在線程啟動(dòng)時(shí)傳遞給線程的委托。
Thread (ThreadStart) 初始化 Thread 類的新實(shí)例。
Thread (ParameterizedThreadStart, Int32) 初始化 Thread 類的新實(shí)例,指定允許對(duì)象在線程啟動(dòng)時(shí)傳遞給線程的委托,并指定線程的最大堆棧大小。
Thread (ThreadStart, Int32) 初始化 Thread 類的新實(shí)例,指定線程的最大堆棧大小。
我們?nèi)绻x不帶參數(shù)的線程,可以用ThreadStart;帶一個(gè)參數(shù)的用ParameterizedThreadStart。帶多個(gè)參數(shù)的用另外的方法,下面逐一講述。
一、不帶參數(shù)的
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!");
}
}
}
二、帶一個(gè)參數(shù)的
由于ParameterizedThreadStart要求參數(shù)類型必須為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 ());
}
}
}
結(jié)果顯示Method B!
三、帶多個(gè)參數(shù)的
由于Thread默認(rèn)只提供了這兩種構(gòu)造函數(shù),如果需要傳遞多個(gè)參數(shù),我們可以自己將參數(shù)作為類的屬性。定義類的對(duì)象時(shí)候?qū)嵗@個(gè)屬性,然后進(jìn)行操作。
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);
}
}
}
結(jié)果顯示x=2,y=3
四、利用結(jié)構(gòu)體給參數(shù)傳值。
定義公用的public struct結(jié)構(gòu)體,里面可以定義自己需要的參數(shù),然后在需要添加線程的時(shí)候,可以定義結(jié)構(gòu)體的實(shí)例。
//結(jié)構(gòu)體
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#中的命名實(shí)參和可選實(shí)參
- 一道關(guān)于C#參數(shù)傳遞的面試題分析
- C#實(shí)現(xiàn)向函數(shù)傳遞不定參數(shù)的方法
- C#傳遞參數(shù)到線程的方法匯總
- C#中的多線程多參數(shù)傳遞詳解
- C#和asp.net中鏈接數(shù)據(jù)庫中參數(shù)的幾種傳遞方法實(shí)例代碼
- C# 運(yùn)用params修飾符來實(shí)現(xiàn)變長參數(shù)傳遞的方法
- c#方法中調(diào)用參數(shù)的值傳遞方式和引用傳遞方式以及ref與out的區(qū)別深入解析
- C#難點(diǎn)逐個(gè)擊破(1):ref參數(shù)傳遞
- asp.net(C#)函數(shù)對(duì)象參數(shù)傳遞的問題
- C# 使用匿名函數(shù)解決EventHandler參數(shù)傳遞的難題
- 理解C#中參數(shù)的值和引用以及傳遞結(jié)構(gòu)和類引用的區(qū)別
相關(guān)文章
VS中C#讀取app.config數(shù)據(jù)庫配置字符串的三種方法
這篇文章主要介紹了VS中C#讀取app.config數(shù)據(jù)庫配置字符串的三種方法,需要的朋友可以參考下2015-10-10C#實(shí)現(xiàn)ListView選中項(xiàng)向上或向下移動(dòng)的方法
這篇文章主要介紹了C#實(shí)現(xiàn)ListView選中項(xiàng)向上或向下移動(dòng)的方法,通過兩個(gè)按鈕點(diǎn)擊事件實(shí)現(xiàn)ListView選中項(xiàng)的上下移動(dòng)功能,需要的朋友可以參考下2015-06-06