线程池ThreadPool.QueueUserWorkItem的问题

xiaoruanzhu 2016-10-25 01:08:36
List<Action> actions = new List<Action>();

actions.Add(()=>{Console.WriteLine("A-1");});
actions.Add(()=>{Console.WriteLine("A-2");});
actions.Add(()=>{Console.WriteLine("A-3");});
actions.Add(()=>{Console.WriteLine("A-4");});

foreach (var action in actions)
{
ThreadPool.UnsafeQueueUserWorkItem(state => action(), null);
}
输出的结果不是按顺序的好理解,可为什么这样书写
foreach (var action in actions)
{
var tempAction = action;
ThreadPool.QueueUserWorkItem(state => tempAction(), null);
}
结果就是按顺序输出呢
...全文
376 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
  • 打赏
  • 举报
回复

List<Action> actions = new List<Action>();

actions.Add(() => { Console.WriteLine("A-1"); });
actions.Add(() => { Console.WriteLine("A-2"); });
actions.Add(() => { Console.WriteLine("A-3"); });
actions.Add(() => { Console.WriteLine("A-4"); });
for (var i = 0; i < 10; i++)
{
foreach (var action in actions)
{
var tempAction = action;
ThreadPool.QueueUserWorkItem(state => tempAction(), null);
}
}

执行结果
Poopaye 2016-10-25
  • 打赏
  • 举报
回复
运气

110,538

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧