Thread.Sleep“中断”任务
所以我有以下代码
Action d = () =>
{
for (int i = 0; i <= 10; i++)
{
Thread.Sleep(50);
Console.WriteLine("Task: {0} log:{1}",Thread.CurrentThread.ManagedThreadId,i);
}
};
Task.Factory.StartNew(d);
但是它没有输出任何内容。但如果我评论 Thread.Sleep,它会按预期工作。使用不同的睡眠值会根据该值获得或多或少的结果。
为什么会这样呢?
So I have the following code
Action d = () =>
{
for (int i = 0; i <= 10; i++)
{
Thread.Sleep(50);
Console.WriteLine("Task: {0} log:{1}",Thread.CurrentThread.ManagedThreadId,i);
}
};
Task.Factory.StartNew(d);
However it doeasn't output anything. But if I comment Thread.Sleep, it works as expected. Playing with different Sleep values gets me more or less results depending on the value.
Why does it happen this way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我怀疑你的程序在任务有机会运行之前就退出了。
默认情况下,任务在线程池线程上运行,这些线程是后台线程。这意味着您的程序不会等待它们完成就退出。
尝试将其添加到您的主线程上:
I suspect your program is exiting before the task has a chance to run.
Tasks run on thread pool threads by default, which are background threads. That means your program doesn't wait for them to finish before exiting.
Try adding this on your main thread:
您是否正在等待任务完成,或者您的程序是否在任务完成之前退出?
Are you waiting for the task to finish anywhere, or does your program quit before the task is done?
我刚刚运行您的代码,它输出:
这是基于我运行的代码应用程序的控制台代码:
I've just run your code and it outputs:
Here is the code of console based on your code app I've run: