当我运行这段代码时,控制台上没有显示任何内容,但当我调试时,它会显示输出。请解释为什么会这样?当线程完成任务时,我如何获取信息?
public class TestClass
{
static void Main()
{
ThreadPool.SetMaxThreads(5, 5);
for (int x = 0; x < 10; x++)
{
ThreadPool.QueueUserWorkItem(new WaitCallback(printnum), x);
}
Console.ReadKey();
}
public static void printnum(object n)
{
Console.WriteLine("Call " + n);
for (int i = 0; i < 10; i++) { Console.WriteLine(i); }
}
}
最佳答案
来自 the documentation对于 Console.ReadKey()
:
The ReadKey method waits, that is, blocks on the thread issuing the ReadKey method, until a character or function key is pressed.
它实际上做的是获取 Console.InternalSyncObject
上的锁,以防止在控制台上进行进一步的操作。
Console.ReadLine()
方法不会以这种方式阻塞线程。您可以改用它。
阅读 this article我猜你安装了 .NET 4.5?
关于c# - 如何在 C# 中使用线程池?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23734710/