前些天出差事情比較少就讀了一下《C# Threading Handbook》,感覺還是收穫不少。現在寫寫自己的體會,希望看到更好的評論,拋磚引玉吧。
該書內容涉及廣泛,我唯寫一些自己認為重要但是自己以前不知道的地方吧。
1、線程的生命週期
System.Threading.Thread類提供了我們start,stop,suspend,resume,join,abort線程的方法。可以通過System.Threading.ThreadState屬性來查看線程的狀態。
The Suspend() method will suspend the current thread indefinitely until another thread wakes it up.
The effect of calling Join() method is that the thread will be blocked until either the other thread completes or the time period elapses, whichever occurs first.
The Abort() method would be very useful, if you want to terminate the thread for whatever reason.
2、適合與不適合使用線程地方
適合使用線程的機會:
a. Background Processes
The first opportunity to spawn a new thread occurs when your application needs to run a large process in the background while still keeping its user interface active and usable.
b. Accessing external resources
The second circumstance in which you might want to consider spawning a new thread occurs when you are accessing resources that are not local to your system.
不適合多線程的場合:
The first is an instance where execution order is extremely important, and the second is a mistake seen quite often in code - creating new threads in a loop.