简体   繁体   English

委托和初次调用的延迟

[英]Delay in delegate.begininvoke and actual invocation

There is delay in the BeginInvoke and actual invoke of the method. BeginInvoke和方法的实际调用存在延迟。

In my code I call method using delegate.BeginInvoke in the for loop and after for loop there is code to wait for all thread to complete. 在我的代码中,我在for循环中使用delegate.BeginInvoke来调用方法,在for循环之后,有代码等待所有线程完成。

for(count=0;count<4; Count;count++)
{
    MethodDelegatedglt;
    dglt = new MethodDelegate(this.ProcessResponse);

    asyncResult = dglt.BeginInvoke(Param1, null, null);
    wHandle.Add(asyncResult.AsyncWaitHandle);
}

logMessage( GUIDSessionXML + " Waiting on all threads to complete.", LogLevel.Debug);

As you can see in above code delegate is define on line 1 and on line 2 it is assigned. 如您在上面的代码中看到的,委托是在第1行定义的,在第2行是分配的。 On line 3 asynchronous call is made and added in waithandle array. 在第3行,进行了异步调用并将其添加到waithandle数组中。

Below I am waiting for the all wait handle to complete 下面我在等待所有等待句柄的完成

if (!System.Threading.WaitHandle.WaitAll(wHandle, connectionTimeOut, false) )
{
   ...      
}

from the log I came to know that method is not called as soon as we call BeginInvoke , there is delay. 从日志中我得知,一旦调用BeginInvoke ,就不会立即调用该方法,这会延迟。

2014-06-20 15:19:42.6104 => Waiting on all threads to complete.
2014-06-20 15:19:44.4044 => Start of ProcessResponse.

as you can see above methods is called after nearly 2 sec. 如您所见,将近2秒钟后就会调用上述方法。

What could be the reason behind this and how it can be fixed, any help on this would be appreciated. 这可能是其背后的原因以及如何解决该问题,对此将提供任何帮助。

Thread pool can be lazy when creating new threads. 创建新线程时,线程池可能是惰性的。 A new thread creation can be delayed for up to 500ms (for more details, check Joe Duffy's "CLR thread pool injection, stuttering problems" ). 新线程的创建最多可以延迟500ms(有关更多详细信息,请参阅Joe Duffy的“ CLR线程池注入,卡顿问题” )。

To account for this behavior, increase the number of pre-allocated threads with ThreadPool.SetMinThreads . 要解决此问题,请使用ThreadPool.SetMinThreads增加预分配线程的数量。

Most likely, you should re-evaluate the design of your application and consider using some modern technologies of parallel programming: Task Parallel Library (TPL) (including Dataflow ), async/await , Reactive Extensions (Rx) . 最有可能的是,您应该重新评估应用程序的设计,并考虑使用一些现代的并行编程技术: 任务并行库(TPL) (包括Dataflow ), async/await响应式扩展(Rx)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM