說起異步,thread,task,async/await,iasyncresult 這些東西肯定是繞不開的,今天就來依次聊聊他們
1.線程(thread)
多線程的意義在于一個應用程序中,有多個執(zhí)行部分可以同時執(zhí)行;對于比較耗時的操作(例如io,數(shù)據(jù)庫操作),或者等待響應(如wcf通信)的操作,可以單獨開啟后臺線程來執(zhí)行,這樣主線程就不會阻塞,可以繼續(xù)往下執(zhí)行;等到后臺線程執(zhí)行完畢,再通知主線程,然后做出對應操作!
在c#中開啟新線程比較簡單
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
static void main( string [] args) { console.writeline( "主線程開始" ); //isbackground=true,將其設置為后臺線程 thread t = new thread(run) { isbackground = true }; t.start(); console.writeline( "主線程在做其他的事!" ); //主線程結束,后臺線程會自動結束,不管有沒有執(zhí)行完成 //thread.sleep(300); thread.sleep(1500); console.writeline( "主線程結束" ); } static void run() { thread.sleep(700); console.writeline( "這是后臺線程調(diào)用" ); } |
執(zhí)行結果如下圖,
可以看到在啟動后臺線程之后,主線程繼續(xù)往下執(zhí)行了,并沒有等到后臺線程執(zhí)行完之后。
1.1 線程池
試想一下,如果有大量的任務需要處理,例如網(wǎng)站后臺對于http請求的處理,那是不是要對每一個請求創(chuàng)建一個后臺線程呢?顯然不合適,這會占用大量內(nèi)存,而且頻繁地創(chuàng)建的過程也會嚴重影響速度,那怎么辦呢?線程池就是為了解決這一問題,把創(chuàng)建的線程存起來,形成一個線程池(里面有多個線程),當要處理任務時,若線程池中有空閑線程(前一個任務執(zhí)行完成后,線程不會被回收,會被設置為空閑狀態(tài)),則直接調(diào)用線程池中的線程執(zhí)行(例asp.net處理機制中的application對象),
使用事例:
1
2
3
4
5
6
7
8
|
for ( int i = 0; i < 10; i++) { threadpool.queueuserworkitem(m => { console.writeline(thread.currentthread.managedthreadid.tostring()); }); } console.read(); |
運行結果:
可以看到,雖然執(zhí)行了10次,但并沒有創(chuàng)建10個線程。
1.2 信號量(semaphore)
semaphore負責協(xié)調(diào)線程,可以限制對某一資源訪問的線程數(shù)量
這里對semaphoreslim類的用法做一個簡單的事例:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
static semaphoreslim semlim = new semaphoreslim(3); //3表示最多只能有三個線程同時訪問 static void main( string [] args) { for ( int i = 0; i < 10; i++) { new thread(semaphoretest).start(); } console.read(); } static void semaphoretest() { semlim.wait(); console.writeline( "線程" + thread.currentthread.managedthreadid.tostring() + "開始執(zhí)行" ); thread.sleep(2000); console.writeline( "線程" + thread.currentthread.managedthreadid.tostring() + "執(zhí)行完畢" ); semlim.release(); } |
執(zhí)行結果如下:
可以看到,剛開始只有三個線程在執(zhí)行,當一個線程執(zhí)行完畢并釋放之后,才會有新的線程來執(zhí)行方法!
除了semaphoreslim類,還可以使用semaphore類,感覺更加靈活,感興趣的話可以搜一下,這里就不做演示了!
2.task
task是.net4.0加入的,跟線程池threadpool的功能類似,用task開啟新任務時,會從線程池中調(diào)用線程,而thread每次實例化都會創(chuàng)建一個新的線程。
1
2
3
4
5
6
7
8
9
10
11
|
console.writeline( "主線程啟動" ); //task.run啟動一個線程 //task啟動的是后臺線程,要在主線程中等待后臺線程執(zhí)行完畢,可以調(diào)用wait方法 //task task = task.factory.startnew(() => { thread.sleep(1500); console.writeline("task啟動"); }); task task = task.run(() => { thread.sleep(1500); console.writeline( "task啟動" ); }); thread.sleep(300); task.wait(); console.writeline( "主線程結束" ); |
執(zhí)行結果如下:
開啟新任務的方法:task.run()或者task.factory.startnew(),開啟的是后臺線程
要在主線程中等待后臺線程執(zhí)行完畢,可以使用wait方法(會以同步的方式來執(zhí)行)。不用wait則會以異步的方式來執(zhí)行。
比較一下task和thread:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
static void main( string [] args) { for ( int i = 0; i < 5; i++) { new thread(run1).start(); } for ( int i = 0; i < 5; i++) { task.run(() => { run2(); }); } } static void run1() { console.writeline( "thread id =" + thread.currentthread.managedthreadid); } static void run2() { console.writeline( "task調(diào)用的thread id =" + thread.currentthread.managedthreadid); } |
執(zhí)行結果:
可以看出來,直接用thread會開啟5個線程,用task(用了線程池)開啟了3個!
2.1 task<tresult>
task<tresult>就是有返回值的task,tresult就是返回值類型。
1
2
3
4
5
6
7
8
9
|
console.writeline( "主線程開始" ); //返回值類型為string task< string > task = task< string >.run(() => { thread.sleep(2000); return thread.currentthread.managedthreadid.tostring(); }); //會等到task執(zhí)行完畢才會輸出; console.writeline(task.result); console.writeline( "主線程結束" ); |
運行結果:
通過task.result可以取到返回值,若取值的時候,后臺線程還沒執(zhí)行完,則會等待其執(zhí)行完畢!
簡單提一下:
task任務可以通過cancellationtokensource類來取消,感覺用得不多,用法比較簡單,感興趣的話可以搜一下!
3. async/await
async/await是c#5.0中推出的,先上用法:
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
|
static void main( string [] args) { console.writeline( "-------主線程啟動-------" ); task< int > task = getstrlengthasync(); console.writeline( "主線程繼續(xù)執(zhí)行" ); console.writeline( "task返回的值" + task.result); console.writeline( "-------主線程結束-------" ); } static async task< int > getstrlengthasync() { console.writeline( "getstrlengthasync方法開始執(zhí)行" ); //此處返回的<string>中的字符串類型,而不是task<string> string str = await getstring(); console.writeline( "getstrlengthasync方法執(zhí)行結束" ); return str.length; } static task< string > getstring() { //console.writeline("getstring方法開始執(zhí)行") return task< string >.run(() => { thread.sleep(2000); return "getstring的返回值" ; }); } |
async用來修飾方法,表明這個方法是異步的,聲明的方法的返回類型必須為:void,task或task<tresult>。
await必須用來修飾task或task<tresult>,而且只能出現(xiàn)在已經(jīng)用async關鍵字修飾的異步方法中。通常情況下,async/await成對出現(xiàn)才有意義,
看看運行結果:
可以看出來,main函數(shù)調(diào)用getstrlengthasync方法后,在await之前,都是同步執(zhí)行的,直到遇到await關鍵字,main函數(shù)才返回繼續(xù)執(zhí)行。
那么是否是在遇到await關鍵字的時候程序自動開啟了一個后臺線程去執(zhí)行getstring方法呢?
現(xiàn)在把getstring方法中的那行注釋加上,運行的結果是:
大家可以看到,在遇到await關鍵字后,沒有繼續(xù)執(zhí)行getstrlengthasync方法后面的操作,也沒有馬上反回到main函數(shù)中,而是執(zhí)行了getstring的第一行,以此可以判斷await這里并沒有開啟新的線程去執(zhí)行getstring方法,而是以同步的方式讓getstring方法執(zhí)行,等到執(zhí)行到getstring方法中的task<string>.run()的時候才由task開啟了后臺線程!
那么await的作用是什么呢?
可以從字面上理解,上面提到task.wait可以讓主線程等待后臺線程執(zhí)行完畢,await和wait類似,同樣是等待,等待task<string>.run()開始的后臺線程執(zhí)行完畢,不同的是await不會阻塞主線程,只會讓getstrlengthasync方法暫停執(zhí)行。
那么await是怎么做到的呢?有沒有開啟新線程去等待?
只有兩個線程(主線程和task開啟的線程)!至于怎么做到的(我也不知道......>_<),大家有興趣的話研究下吧!
4.iasyncresult
iasyncresult自.net1.1起就有了,包含可異步操作的方法的類需要實現(xiàn)它,task類就實現(xiàn)了該接口
在不借助于task的情況下怎么實現(xiàn)異步呢?
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
|
class program { static void main( string [] args) { console.writeline( "主程序開始--------------------" ); int threadid; asyncdemo ad = new asyncdemo(); asyncmethodcaller caller = new asyncmethodcaller(ad.testmethod); iasyncresult result = caller.begininvoke(3000, out threadid, null , null ); thread.sleep(0); console.writeline( "主線程線程 {0} 正在運行." ,thread.currentthread.managedthreadid) //會阻塞線程,直到后臺線程執(zhí)行完畢之后,才會往下執(zhí)行 result.asyncwaithandle.waitone(); console.writeline( "主程序在做一些事情!!!" ); //獲取異步執(zhí)行的結果 string returnvalue = caller.endinvoke( out threadid, result); //釋放資源 result.asyncwaithandle.close(); console.writeline( "主程序結束--------------------" ); console.read(); } } public class asyncdemo { //供后臺線程執(zhí)行的方法 public string testmethod( int callduration, out int threadid) { console.writeline( "測試方法開始執(zhí)行." ); thread.sleep(callduration); threadid = thread.currentthread.managedthreadid; return string .format( "測試方法執(zhí)行的時間 {0}." , callduration.tostring()); } } public delegate string asyncmethodcaller( int callduration, out int threadid); |
關鍵步驟就是紅色字體的部分,運行結果:
和task的用法差異不是很大!result.asyncwaithandle.waitone()就類似task的wait。
5.parallel
最后說一下在循環(huán)中開啟多線程的簡單方法:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
stopwatch watch1 = new stopwatch(); watch1.start(); for ( int i = 1; i <= 10; i++) { console.write(i + "," ); thread.sleep(1000); } watch1.stop(); console.writeline(watch1.elapsed); stopwatch watch2 = new stopwatch(); watch2.start(); //會調(diào)用線程池中的線程 parallel. for (1, 11, i => { console.writeline(i + ",線程id:" + thread.currentthread.managedthreadid); thread.sleep(1000); }); watch2.stop(); console.writeline(watch2.elapsed); |
運行結果:
循環(huán)list<t>:
1
2
3
4
5
6
|
list< int > list = new list< int >() { 1, 2, 3, 4, 5, 6, 6, 7, 8, 9 }; parallel. foreach < int >(list, n => { console.writeline(n); thread.sleep(1000); }); |
執(zhí)行action[]數(shù)組里面的方法:
1
2
3
4
5
6
7
8
9
|
action[] actions = new action[] { new action(()=>{ console.writeline( "方法1" ); }), new action(()=>{ console.writeline( "方法2" ); }) }; parallel.invoke(actions); |
以上就是本文的全部內(nèi)容,希望本文的內(nèi)容對大家的學習或者工作能帶來一定的幫助,同時也希望多多支持服務器之家!
原文鏈接:http://www.cnblogs.com/doforfuture/p/6293926.html