Threads are responsible for multitasking within a single application.You may never need to manage threads explicitly,because the CLR abstracts much of the thread support into classes that simplify most threading tasks.Even if you don`t create your own threads explicitly,you`ll ensure that your code can handle multiple threads if it`s run in a multithreading environment.The concern is especially important if you are creating components that mught be used by other programmers in a program that supports multithreading.It is particularly significant to remoting and web services developers.Although web services have many attributes of desktop applications,they are run on the server ,generally lack a user interface ,and force the developer to think about server-side issues such as efficiency and multithreading.
1.创建线程
CLR定义了ThreadStart委托,public delegate void ThreadStart();看代码
以前我看见过一些代码,有的要求必须主线程结束之后,新创建的线程才能结束,但是在这里,很明显主线程应该早已结束,但是为什么新创建的线程还能继续运行呢?原来线程分为前台线程和后台线程。这两种线程的区别是:当前台程序全部结束时,程序结束。此时不管后台程序有没有完毕,通通结束,也就是说前台线程是决定程序结束的关键,后台线程没有决定权,当前台线程通通结束时,他们就得结束。 通过IsBackground属性可以查看或者设置线程的前后台情况。我们通过Thread创建的线程默认情况下是前台的,所以程序会等我们的线程通通运行结束才会结束,但是下面的例子就不行了,你会发现新创建的线程根本没有运行:因为通过BeginInvoke调用的线程都是后台线程,前台线程main一结束,整个程序就结束了。
2.关于Join-直到join的线程运行结束才往下运行.例如下面的例子,开始是main和DoTest中的thread并行运行,当beforemain运行结束后,Join的线程把main挂起,自己和thread并行运行,直到自己运行结束,main才继续得以运行。这相当于是一个插队,暂时取代别人把自己当做和外面线程并行运行的代表。
3.终止线程-这里的join是为了不想主函数的writeline在线程结束之前运行。
4.同步-看如下代码
使用Interlocked,还是不对
问题慢慢分析吧。。
这里我有一个疑问?
int temp = (a+1);是有几条语句