C#實(shí)現(xiàn)向多線程傳參的三種方式實(shí)例分析
本文實(shí)例講述了C#實(shí)現(xiàn)向多線程傳參的三種方式。分享給大家供大家參考,具體如下:
從《C#高級(jí)編程》了解到給線程傳遞參數(shù)有兩種方式,一種方式是使用帶ParameterizedThreadStart委托參數(shù)的Thread構(gòu)造函數(shù),另一種方式是創(chuàng)建一個(gè)自定義類,把線程的方法定義為實(shí)例的方法,這樣就可以初始化實(shí)例的數(shù)據(jù),之后啟動(dòng)線程。
方式一:使用ParameterizedThreadStart委托
如果使用了ParameterizedThreadStart委托,線程的入口必須有一個(gè)object類型的參數(shù),且返回類型為void。且看下面的例子:
using System; using System.Threading; namespace ThreadWithParameters { class Program { static void Main(string[] args) { string hello = "hello world"; //這里也可簡(jiǎn)寫成Thread thread = new Thread(ThreadMainWithParameters); //但是為了讓大家知道這里用的是ParameterizedThreadStart委托,就沒(méi)有簡(jiǎn)寫了 Thread thread = new Thread(new ParameterizedThreadStart(ThreadMainWithParameters)); thread.Start(hello); Console.Read(); } static void ThreadMainWithParameters(object obj) { string str = obj as string; if(!string.IsNullOrEmpty(str)) Console.WriteLine("Running in a thread,received: {0}", str); } } }
這里稍微有點(diǎn)麻煩的就是ThreadMainWithParameters方法里的參數(shù)必須是object類型的,我們需要進(jìn)行類型轉(zhuǎn)換。為什么參數(shù)必須是object類型呢,各位看看ParameterizedThreadStart委托的聲明就知道了。
public delegate void ParameterizedThreadStart(object obj); //ParameterizedThreadStart委托的聲明
方式二:創(chuàng)建自定義類
定義一個(gè)類,在其中定義需要的字段,將線程的主方法定義為類的一個(gè)實(shí)例方法,說(shuō)得不是很明白,還是看實(shí)際的例子吧。
using System; using System.Threading; namespace ThreadWithParameters { public class MyThread { private string data; public MyThread(string data) { this.data = data; } public void ThreadMain() { Console.WriteLine("Running in a thread,data: {0}", data); } } class Program { static void Main(string[] args) { MyThread myThread = new MyThread("hello world"); Thread thread = new Thread(myThread.ThreadMain); thread.Start(); Console.Read(); } } }
對(duì)這種方法也不是很滿意,總不能一遇到比較耗時(shí)的方法,就新建一個(gè)類吧。。。
那有什么更好辦法即不用強(qiáng)制類型轉(zhuǎn)換,也不用新建一個(gè)類呢?
下面就介紹下我無(wú)意中找到的一個(gè)方法,具體是在哪見(jiàn)過(guò)的我也不記得了,罪過(guò)啊。。
方式三:使用匿名方法
using System; using System.Threading; namespace ThreadWithParameters { class Program { static void Main(string[] args) { string hello = "hello world"; //如果寫成Thread thread = new Thread(ThreadMainWithParameters(hello));這種形式,編譯時(shí)就會(huì)報(bào)錯(cuò) Thread thread = new Thread(() => ThreadMainWithParameters(hello)); thread.Start(); Console.Read(); } static void ThreadMainWithParameters(string str) { Console.WriteLine("Running in a thread,received: {0}", str); } } }
哇,你會(huì)發(fā)現(xiàn)既不用類型強(qiáng)制轉(zhuǎn)換也不用新建類就運(yùn)行成功了。
但是為什么這種方式能行呢,根據(jù)昨天 @亂舞春秋 的提示,我也用ildasm反編譯了一下,確實(shí)如他所說(shuō),我所謂的第三種方式其實(shí)和第二種方式是一樣的,只不過(guò)自定義類編譯器幫我們做了。
下面的是第三種方式main方法反編譯的IL代碼:
.method private hidebysig static void Main(string[] args) cil managed { .entrypoint // 代碼大小 51 (0x33) .maxstack 3 .locals init ([0] class [mscorlib]System.Threading.Thread thread, [1] class ThreadWithParameters.Program/'<>c__DisplayClass1' 'CS$<>8__locals2') IL_0000: newobj instance void ThreadWithParameters.Program/'<>c__DisplayClass1'::.ctor() IL_0005: stloc.1 IL_0006: nop IL_0007: ldloc.1 IL_0008: ldstr "hello world" IL_000d: stfld string ThreadWithParameters.Program/'<>c__DisplayClass1'::hello IL_0012: ldloc.1 IL_0013: ldftn instance void ThreadWithParameters.Program/'<>c__DisplayClass1'::'<Main>b__0'() IL_0019: newobj instance void [mscorlib]System.Threading.ThreadStart::.ctor(object, native int) IL_001e: newobj instance void [mscorlib]System.Threading.Thread::.ctor(class [mscorlib]System.Threading.ThreadStart) IL_0023: stloc.0 IL_0024: ldloc.0 IL_0025: callvirt instance void [mscorlib]System.Threading.Thread::Start() IL_002a: nop IL_002b: call int32 [mscorlib]System.Console::Read() IL_0030: pop IL_0031: nop IL_0032: ret } // end of method Program::Main
在看看第二種方式的IL代碼:
.method private hidebysig static void Main(string[] args) cil managed { .entrypoint // 代碼大小 44 (0x2c) .maxstack 3 .locals init ([0] class ThreadWithParameters.MyThread myThread, [1] class [mscorlib]System.Threading.Thread thread) IL_0000: nop IL_0001: ldstr "hello world" IL_0006: newobj instance void ThreadWithParameters.MyThread::.ctor(string) IL_000b: stloc.0 IL_000c: ldloc.0 IL_000d: ldftn instance void ThreadWithParameters.MyThread::ThreadMain() IL_0013: newobj instance void [mscorlib]System.Threading.ThreadStart::.ctor(object, native int) IL_0018: newobj instance void [mscorlib]System.Threading.Thread::.ctor(class [mscorlib]System.Threading.ThreadStart) IL_001d: stloc.1 IL_001e: ldloc.1 IL_001f: callvirt instance void [mscorlib]System.Threading.Thread::Start() IL_0024: nop IL_0025: call int32 [mscorlib]System.Console::Read() IL_002a: pop IL_002b: ret } // end of method Program::Main
比較兩端代碼,可以發(fā)現(xiàn)兩者都有一個(gè)newobj,這句的作用是初始化一個(gè)類的實(shí)例,第三種方式由編譯器生成了一個(gè)類:c__DisplayClass1
IL_0000: newobj instance void ThreadWithParameters.Program/'<>c__DisplayClass1'::.ctor() IL_0006: newobj instance void ThreadWithParameters.MyThread::.ctor(string)
注意:簡(jiǎn)單并不一定是好事,匿名方法容易造成不易察覺(jué)的錯(cuò)誤
希望本文所述對(duì)大家C#程序設(shè)計(jì)有所幫助。
- C#解決SQlite并發(fā)異常問(wèn)題的方法(使用讀寫鎖)
- 如何使用C#讀寫鎖ReaderWriterLockSlim
- 解析C#多線程編程中異步多線程的實(shí)現(xiàn)及線程池的使用
- C#基于委托實(shí)現(xiàn)多線程之間操作的方法
- C#實(shí)現(xiàn)多線程寫入同一個(gè)文件的方法
- C#實(shí)現(xiàn)多線程下載文件的方法
- C#如何對(duì)多線程、多任務(wù)管理(demo)
- C#實(shí)現(xiàn)多線程的Web代理服務(wù)器實(shí)例
- C#使用Parallel類進(jìn)行多線程編程實(shí)例
- C#使用讀寫鎖三行代碼簡(jiǎn)單解決多線程并發(fā)的問(wèn)題
相關(guān)文章
深入分析緩存依賴中cachedependency對(duì)象及周邊小講
本篇文章是對(duì)緩存依賴中cachedependency對(duì)象進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下2013-06-06C# SendInput 模擬鼠標(biāo)操作的實(shí)現(xiàn)方法
C# SendInput 模擬鼠標(biāo)操作的實(shí)現(xiàn)方法,需要的朋友可以參考一下2013-04-04C#多線程之Thread中Thread.IsAlive屬性用法分析
這篇文章主要介紹了C#多線程之Thread中Thread.IsAlive屬性用法,實(shí)例分析了C#判斷線程可用狀態(tài)的技巧,非常具有實(shí)用價(jià)值,需要的朋友可以參考下2015-04-04WinForm 自動(dòng)完成控件實(shí)例代碼簡(jiǎn)析
在Web的應(yīng)用方面有js的插件實(shí)現(xiàn)自動(dòng)完成(或叫智能提示)功能,但在WinForm窗體應(yīng)用方面就沒(méi)那么好了,接下來(lái)參考一下這個(gè)實(shí)例,看看有沒(méi)有以外收獲,感興趣的朋友可以了解下啊,希望本文對(duì)你有幫助啊2013-01-01Unity游戲開(kāi)發(fā)之射擊小游戲的實(shí)現(xiàn)
本篇文章為大家?guī)?lái)一個(gè)橫版2D射擊小游戲,游戲制作超級(jí)簡(jiǎn)單,玩法一學(xué)就會(huì)。文中的示例代碼講解詳細(xì),快跟隨小編一起動(dòng)手試一試2022-03-03