委托
對于委托,我們都知道他是一個引用類型,具有引用類型所具有的通性。需要知道的是它保存的不是實(shí)際值,只是是保存對存儲在托管堆中的對象的引用。或說的直接點(diǎn),委托就相當(dāng)于叫人幫忙,讓你幫你做一些事情。我這里就使用委托的形式,調(diào)用線程,來簡單的說一下。
代碼如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
|
using system; using system.threading; namespace _012_線程 { class program { static void main( string [] args) //在mian中線程是執(zhí)行一個線程里面的語句的執(zhí)行,是從上到下的 { //通過委托 開啟一個線程 //==============可用泛型傳參數(shù)(無返回值)============== action threaa = threadtesta; threaa.begininvoke( null , null ); //開啟一個新的線程去執(zhí)行,threaa所引用的方法 action< int > threab = threadtestb; threab.begininvoke(111, null , null ); //可以認(rèn)為線程是同時執(zhí)行的 (異步執(zhí)行) console.writeline( "異步執(zhí)行" ); //================帶返回值的形式==================== //第一種方式 檢測線程結(jié)束 ----- iscompleted線程是否行完畢 //func<int, int> threac = threadtestc; ////接收異步線程返回值 //iasyncresult returnresult = threac.begininvoke(111, null, null); //while (!res.iscompleted) //{ // console.write("."); // thread.sleep(10); //控制子線程的檢測頻率,(每10ms檢測一次) //} ////取得異步線程返回值 //int result = threac.endinvoke(res); //console.writeline("iscompleted方式檢測:" + result); //第二種方式 檢測線程結(jié)束 ----- 1000ms沒結(jié)束就返回false,反之 func< int , int > threac = threadtestc; //接收異步線程返回值 iasyncresult returnresult = threac.begininvoke(111, null , null ); bool isend = returnresult.asyncwaithandle.waitone(1000); int result = 0; if (isend) { result = threac.endinvoke(returnresult); } console.writeline( "endinvoke()方式檢測:" + isend + " " + result); //第三種方式 檢測線程結(jié)束 ----- 通過回調(diào),檢測線程結(jié)束 func< int , string , string > thread = threadtestd; //倒數(shù)第二個參數(shù),表示委托類型的參數(shù),(回調(diào)函數(shù))當(dāng)線程結(jié)束的時候會調(diào)用這個委托指向的方法 //最后一個參數(shù),用來給回調(diào)函數(shù)傳遞數(shù)據(jù) iasyncresult asy = thread.begininvoke(111, "czhenya" , oncallkey, thread); //改為lamdba表達(dá)式 thread.begininvoke(111, "czhenya" ,(ar)=>{ string res = thread.endinvoke(ar); console.writeline( "在lamdba表達(dá)式中取得:" +res); }, null ); console.readkey(); } static void oncallkey(iasyncresult ar) { func< int , string , string > thread = ar.asyncstate as func< int , string , string >; string res = thread.endinvoke(ar); console.writeline( "在回調(diào)函數(shù)中取到的結(jié)果 :" +res); } /// <summary> /// 一般是比較耗時的操作方法 /// </summary> static void threadtesta() { console.writeline( "threatesta" ); } static void threadtestb( int num) { console.writeline( "threatestb " +num); } static int threadtestc( int num) { console.writeline( "threatestc" ); thread.sleep(100); //讓當(dāng)前線程休眠(暫停線程(參數(shù)單位:ms)) return num; } static string threadtestd( int num, string str) { console.writeline( "threatestd" ); return num + " " + str; } } } |
運(yùn)行結(jié)果圖:
總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,謝謝大家對服務(wù)器之家的支持。如果你想了解更多相關(guān)內(nèi)容請查看下面相關(guān)鏈接
原文鏈接:https://blog.csdn.net/Czhenya/article/details/78225963