您的位置:首页 > 其它

线程

2016-07-08 11:44 148 查看

AppDomain,进程和线程的关系

还是用图来说明比较容易理解。

1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5 using System.Threading;
6 using System.Threading.Tasks;
7
8 namespace AsyncCoding
9 {
10     class Program
11     {
12         static void Main(string[] args)
13         {
14             var thread1 = new Thread(Go1);
15             thread1.IsBackground = true;//默认为前台线程
16             thread1.Start();//启动线程
17
18             Console.WriteLine("我是主线程,Thread Id:{0}", Thread.CurrentThread.ManagedThreadId);
19
20             Thread.Sleep(500);//挂起线程,模拟等待异步线程做事情
21             thread1.Abort();//结束异步线程
22
23             Console.ReadKey();
24         }
25
26         public static void Go1()
27         {
28             Console.WriteLine("我是异步线程,Thread Id:{0}", Thread.CurrentThread.ManagedThreadId);
29
30             try
31             {
32                 for (int i = 0; i < 10; i++)
33                 {
34                     Thread.Sleep(100);//模拟每次执行需要100ms
35                     Console.WriteLine("异步线程运行:{0}", i);
36                 }
37             }
38             catch (ThreadAbortException ex)
39             {
40                 Console.WriteLine("异步线程被强制结束!");
41             }
42         }
43     }
44 }


View Code

代码运行顺序。





运行结果。



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: