BeginInvoke:调用过多
请看下面的代码。
for (int j = 0; j < 500000; j++)
{
Console.WriteLine(j);
// Call BeginInvoke with last two parameters as null
IAsyncResult asyncRes = dlg.BeginInvoke(j, 4, ref refString, out outString, progressCallBack, null);
}
如果异步调用的方法休眠 5 分钟。那么创建了 5 个 lac 线程是否正确?
谢谢。
pls look at following piece of code.
for (int j = 0; j < 500000; j++)
{
Console.WriteLine(j);
// Call BeginInvoke with last two parameters as null
IAsyncResult asyncRes = dlg.BeginInvoke(j, 4, ref refString, out outString, progressCallBack, null);
}
if the method that is being invoked asynchronously sleeps for 5 mins. then is it correct that 5 lac threads have been created?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这通常是不正确的。当您在委托上调用
BeginInvoke
时,您正在排队异步方法执行。.NET 线程池 将根据需要处理的工作项队列决定何时以及如何执行您的方法,并以最大吞吐量为目标,但它肯定不会并行运行 500000 个线程。
当我尝试你的示例时,睡眠时间为 5 分钟,并且委托中出现了一条小控制台消息,最初只有 8 个线程在运行,然后慢慢地更多线程开始运行。
有关线程池和异步委托的详细解释,请阅读 本文。
That is generally not true. When you call
BeginInvoke
on a delegate, you are queuing up an asynchronous method execution.The .NET Threadpool will decide when and how to execute your method based on the queue of work items that need processing and with the aim for maximum throughput, but certainly it will not run 500000 threads in parallel.
When I tried out your example with a sleep of 5 minutes and a little console message in the delegate only 8 threads were running initially, then slowly more were trickling in.
For a good explanation on the thread pool and asynchronous delegates read this article.