C#線程傳遞參數(shù)實(shí)現(xiàn)淺析
C#線程傳遞參數(shù)的實(shí)現(xiàn)是如何進(jìn)行的呢?那么這里我們使用MyThread來為線程傳遞任意復(fù)雜的參數(shù),那么下面就向你詳細(xì)介紹具體的實(shí)現(xiàn)過程。
Thread類有一個(gè)帶參數(shù)的委托類型的重載形式。這個(gè)委托的定義如下:
- [ComVisibleAttribute(false)]
- public delegate void ParameterizedThreadStart(Object obj)
C#線程傳遞參數(shù)之Thread類的構(gòu)造方法的定義如下:
- public Thread(ParameterizedThreadStart start);
下面的代碼使用了這個(gè)帶參數(shù)的委托向線程傳遞一個(gè)字符串參數(shù):
- public static void myStaticParamThreadMethod(Object obj)
- {
- Console.WriteLine(obj);
- }
- static void Main(string[] args)
- {
- Thread thread = new Thread(myStaticParamThreadMethod);
- thread.Start("通過委托的參數(shù)傳值");
- }
要注意的是,如果使用的是不帶參數(shù)的委托,不能使用帶參數(shù)的Start方法運(yùn)行線程,否則系統(tǒng)會(huì)拋出異常。但使用帶參數(shù)的委托,可以使用thread.Start()來運(yùn)行線程,這時(shí)所傳遞的參數(shù)值為null。
C#線程傳遞參數(shù)之定義一個(gè)類來傳遞參數(shù)值:
實(shí)現(xiàn)具體的代碼如下:
- class MyData
- {
- private String d1;
- private int d2;
- public MyData(String d1, int d2)
- {
- this.d1 = d1;
- this.d2 = d2;
- }
- public void threadMethod()
- {
- Console.WriteLine(d1);
- Console.WriteLine(d2);
- }
- }
- MyData myData = new MyData("abcd",1234);
- Thread thread = new Thread(myData.threadMethod);
- thread.Start();
如果使用MyThread類,傳遞參數(shù)會(huì)顯示更簡(jiǎn)單:
- class NewThread : MyThread
- {
- private String p1;
- private int p2;
- public NewThread(String p1, int p2)
- {
- this.p1 = p1;
- this.p2 = p2;
- }
- override public void run()
- {
- Console.WriteLine(p1);
- Console.WriteLine(p2);
- }
- }
- NewThread newThread = new NewThread("hello world", 4321);
- newThread.start();
C#線程傳遞參數(shù)的相關(guān)內(nèi)容就向你介紹到這里,希望對(duì)你了解和學(xué)習(xí)C#線程傳遞參數(shù)有所幫助。
【編輯推薦】