开发者

Avoid memory leak on Async timeout

I'm trying to find a memory leak in my application and I want to know if I must (or should) call EndInvoke in case of a timeout. I'm calling a external system and I must have a way to stop waiting if execution is too long:

Dim ar As IAsyncResult
Try
  ar = deleg.BeginInvoke(Nothing, New Object)
  If Not ar.AsyncWaitHandle.WaitOne(getTimeout, False) Then
    'Should I call EndIn开发者_如何学JAVAvoke here
    Throw New Exceptions.TimeoutException
  Else
    response = deleg.EndInvoke(ar)
  End If
Finally
  ar = Nothing
End Try

Thanks


Yes, you do need to call EndInvoke. But you can't call it in a timeout situation (or else it would block on the operation, defeating the purpose of asynchronous execution and timeouts).

One option is to toss it into the thread pool. You can pass the AsyncWaitHandle to ThreadPool.RegisterWaitForSingleObject and have the callback call EndInvoke (being sure to catch exceptions). However, this approach does not scale (only 64 handles can be outstanding on the thread pool at any given time).

A better option is to use the new Task abstraction in .NET 4.0 (also available in .NET 3.5 if you use Rx). It's much easier to work with.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜