首页 新闻 会员 周边 捐助

C# Task Action 为什么会执行 两次?

0
悬赏园豆:5 [已关闭问题] 关闭于 2014-01-16 17:13

 1 class Program
 2     {
 3         static List<Task> tkList = new List<Task>();
 4         static int taskCount = 5;
 5         static object obj = new object();
 6 
 7         static void Main(string[] args)
 8         {
 9             Console.WriteLine("开始任务");
10             for (int i = 0; i < 100; i++)
11             {
12                 while(!isGo())
13                 {
14                     Thread.Sleep(100);
15                 }
16                 Action<object> action = action = new Action<object>(Print);
17                 CreatTask(action, i);
18             }
19             Console.WriteLine("任务完成!");
20             Console.Read();
21         }
22 
23 
24         public static bool isGo()
25         {
26             bool flag =false;
27 
28             if (tkList.Count == 0||tkList.Count < taskCount)
29             {
30                 flag = true;
31             }
32             else
33             {
34                 foreach (Task item in tkList)
35                 {
36                     if (item.IsCompleted)
37                     {
38                         Console.WriteLine(item.AsyncState.ToString());
39                         tkList.Remove(item);
40                         item.Dispose();
41                         flag = true;
42                         break;
43                     }
44                 }                
45             }
46             return flag;
47         }
48 
49         public static void CreatTask(Action<object> action,object obj)
50         { 
51             Task t = Task.Factory.StartNew(action, obj);               
52             tkList.Add(t);                
53         }
54 
55         public static void Print(object msg)
56         {
57             Console.WriteLine(msg);
58         }
59     }
ywspace的主页 ywspace | 初学一级 | 园豆:199
提问于:2014-01-16 17:02
< >
分享
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册