From fee08d8608b62835f0f6b34cff14a1eb1a1f96c6 Mon Sep 17 00:00:00 2001 From: Menachem Hornbacher Date: Mon, 7 Dec 2020 20:11:37 -0500 Subject: [PATCH] fix memory leak #1506 --- src/RestSharp/Http.Async.cs | 21 ++++++++++++++++----- 1 file changed, 16 insertions(+), 5 deletions(-) diff --git a/src/RestSharp/Http.Async.cs b/src/RestSharp/Http.Async.cs index 735d8a9cb..e0db03a1f 100644 --- a/src/RestSharp/Http.Async.cs +++ b/src/RestSharp/Http.Async.cs @@ -173,20 +173,29 @@ long CalculateContentLength() void SetTimeout(IAsyncResult asyncResult) { if (Timeout != 0) - ThreadPool.RegisterWaitForSingleObject( + _timeoutState.Handle = ThreadPool.RegisterWaitForSingleObject( asyncResult.AsyncWaitHandle, TimeoutCallback, _timeoutState, Timeout, true ); static void TimeoutCallback(object state, bool timedOut) { - if (!timedOut) - return; - if (!(state is TimeOutState tos)) return; - lock (tos) tos.TimedOut = true; + lock(tos) + { + if(!timedOut) + { + if(tos.Handle != null) + { + tos.Handle.Unregister(null); + } + return; + } + + tos.TimedOut = true; + } tos.Request?.Abort(); } @@ -286,6 +295,8 @@ class TimeOutState public bool TimedOut { get; set; } public HttpWebRequest? Request { get; set; } + + public RegisteredWaitHandle? Handle { get; set; } } } } \ No newline at end of file