From 2290fadf9af86059f6fbf4b21ae2b154e6c3b927 Mon Sep 17 00:00:00 2001 From: Rolf Bjarne Kvinge Date: Fri, 15 Mar 2024 18:21:47 +0100 Subject: [PATCH] [Foundation] Don't dispose the CancellationTokenSource in NSUrlSessionHandler's InflightData. Fixes #11799. There's a random ObjectDisposedException occurring, which seems to have this sequence of events: 1. The request is sent. 2. The request is cancelled. 3. The InflightData instance is removed here: https://github.com/xamarin/xamarin-macios/blob/c3437328bf2c02d03a6d4dc4e752ef8ac927ca4e/src/Foundation/NSUrlSessionHandler.cs#L545 3a. The InflightData is disposed: https://github.com/xamarin/xamarin-macios/blob/c3437328bf2c02d03a6d4dc4e752ef8ac927ca4e/src/Foundation/NSUrlSessionHandler.cs#L224 3a. The InflightData.CancellationTokenSource instance is disposed: https://github.com/xamarin/xamarin-macios/blob/c3437328bf2c02d03a6d4dc4e752ef8ac927ca4e/src/Foundation/NSUrlSessionHandler.cs#L1168 4. Data comes in (in the DidReceiveData callback), and SetResponse is called: https://github.com/xamarin/xamarin-macios/blob/c3437328bf2c02d03a6d4dc4e752ef8ac927ca4e/src/Foundation/NSUrlSessionHandler.cs#L932 4a. The SetResponse method tries to use InflightData.CancellationTokenSource, and that throws an ObjectDisposedException: https://github.com/xamarin/xamarin-macios/blob/c3437328bf2c02d03a6d4dc4e752ef8ac927ca4e/src/Foundation/NSUrlSessionHandler.cs#L970 Full stack traces: ``` InflightData disposed: at System.Net.Http.NSUrlSessionHandler.InflightData.Dispose(Boolean disposing) in xamarin-macios/src/Foundation/NSUrlSessionHandler.cs:line 1168 at System.Net.Http.NSUrlSessionHandler.InflightData.Dispose() in xamarin-macios/src/Foundation/NSUrlSessionHandler.cs:line 1160 at System.Net.Http.NSUrlSessionHandler.RemoveInflightData(NSUrlSessionTask task, Boolean cancel) in xamarin-macios/src/Foundation/NSUrlSessionHandler.cs:line 224 at System.Net.Http.NSUrlSessionHandler.<>c__DisplayClass58_0.b__0() in xamarin-macios/src/Foundation/NSUrlSessionHandler.cs:line 545 at System.Threading.CancellationToken.<>c.b__12_0(Object obj) at System.Threading.CancellationTokenSource.Invoke(Delegate d, Object state, CancellationTokenSource source) at System.Threading.CancellationTokenSource.CallbackNode.<>c.b__9_0(Object s) at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state) at System.Threading.CancellationTokenSource.CallbackNode.ExecuteCallback() at System.Threading.CancellationTokenSource.ExecuteCallbackHandlers(Boolean throwOnFirstException) at System.Threading.CancellationTokenSource.NotifyCancellation(Boolean throwOnFirstException) at System.Threading.CancellationTokenSource.LinkedNCancellationTokenSource.<>c.<.cctor>b__4_0(Object s) at System.Threading.CancellationTokenSource.Invoke(Delegate d, Object state, CancellationTokenSource source) at System.Threading.CancellationTokenSource.CallbackNode.ExecuteCallback() at System.Threading.CancellationTokenSource.ExecuteCallbackHandlers(Boolean throwOnFirstException) at System.Threading.CancellationTokenSource.NotifyCancellation(Boolean throwOnFirstException) at System.Threading.CancellationTokenSource.TimerCallback(Object state) at System.Threading.TimerQueueTimer.CallCallback(Boolean isThreadPool) at System.Threading.TimerQueueTimer.Fire(Boolean isThreadPool) at System.Threading.TimerQueue.FireNextTimers() at System.Threading.TimerQueue.System.Threading.IThreadPoolWorkItem.Execute() at System.Threading.ThreadPoolWorkQueue.DispatchItemWithAutoreleasePool(Object workItem, Thread currentThread) at System.Threading.ThreadPoolWorkQueue.Dispatch() at System.Threading.PortableThreadPool.WorkerThread.WorkerThreadStart() at System.Threading.Thread.StartCallback() ``` ``` ObjectDisposedException: *** Terminating app due to uncaught exception 'System.ObjectDisposedException', reason: 'The CancellationTokenSource has been disposed. (System.ObjectDisposedException) at System.Net.Http.NSUrlSessionHandler.NSUrlSessionHandlerDelegate.SetResponse(InflightData inflight) in xamarin-macios/src/Foundation/NSUrlSessionHandler.cs:line 970 at System.Net.Http.NSUrlSessionHandler.NSUrlSessionHandlerDelegate.DidReceiveData(NSUrlSession session, NSUrlSessionDataTask dataTask, NSData data) in xamarin-macios/src/Foundation/NSUrlSessionHandler.cs:line 932 ' *** First throw call stack: ( 0 CoreFoundation 0x0000000186e72ccc __exceptionPreprocess + 176 1 libobjc.A.dylib 0x000000018695a788 objc_exception_throw + 60 2 nsurlsessionhandler 0x0000000106d4562c xamarin_process_managed_exception + 1052 3 nsurlsessionhandler 0x00000001071a26c4 _ZL31native_to_managed_trampoline_53P11objc_objectP13objc_selectorPP11_MonoMethodS0_S0_S0_j + 1028 4 nsurlsessionhandler 0x00000001071ca8e0 -[System_Net_Http_NSUrlSessionHandler_NSUrlSessionHandlerDelegate URLSession:dataTask:didReceiveData:] + 68 5 CFNetwork 0x000000018c0fe28c CFURLCredentialStorageCopyAllCredentials + 61900 6 libdispatch.dylib 0x0000000186b6c750 _dispatch_call_block_and_release + 32 7 libdispatch.dylib 0x0000000186b6e3e8 _dispatch_client_callout + 20 8 libdispatch.dylib 0x0000000186b75a14 _dispatch_lane_serial_drain + 748 9 libdispatch.dylib 0x0000000186b76578 _dispatch_lane_invoke + 432 10 libdispatch.dylib 0x0000000186b812d0 _dispatch_root_queue_drain_deferred_wlh + 288 11 libdispatch.dylib 0x0000000186b80b44 _dispatch_workloop_worker_thread + 404 12 libsystem_pthread.dylib 0x0000000186d1b00c _pthread_wqthread + 288 13 libsystem_pthread.dylib 0x0000000186d19d28 start_wqthread + 8 ``` Disposing the CancellationTokenSource would be ideal, but the additional complexity this would entail makes me question whether it's worth it: the amount of entry points into this code makes it quite complex to keep track of what the request has done, what it's doing and what's pending when things can happen simultaneously on multiple threads at the same time, and keeping the code thread-safe, and at the same time not accidentally not run into deadlocks. So it seems an easy fix would be to just not dispose the CancellationTokenSource, the GC will eventually do it, even though MSDN [says][1] quite clearly: > Always call Dispose before you release your last reference to the CancellationTokenSource. Otherwise, the resources it is using will not be freed until the garbage collector calls the CancellationTokenSource object's Finalize method. An additional note is that a network request's resource usage would already be dwarfing any memory usage by the CancellationTokenSource, so it's unlikely this will show up in any profiles. So with this change we won't be disposing the CancellationTokenSource anymore. Fixes https://github.com/xamarin/xamarin-macios/issues/11799. [1]: https://learn.microsoft.com/en-us/dotnet/api/system.threading.cancellationtokensource.dispose?view=net-8.0 --- src/Foundation/NSUrlSessionHandler.cs | 19 +------------------ 1 file changed, 1 insertion(+), 18 deletions(-) diff --git a/src/Foundation/NSUrlSessionHandler.cs b/src/Foundation/NSUrlSessionHandler.cs index 1cd080833288..f3b099e4872b 100644 --- a/src/Foundation/NSUrlSessionHandler.cs +++ b/src/Foundation/NSUrlSessionHandler.cs @@ -221,7 +221,6 @@ void RemoveInflightData (NSUrlSessionTask task, bool cancel = true) if (inflightRequests.TryGetValue (task, out var data)) { if (cancel) data.CancellationTokenSource.Cancel (); - data.Dispose (); inflightRequests.Remove (task); } #if !MONOMAC && !__WATCHOS__ && !NET8_0 @@ -247,7 +246,6 @@ protected override void Dispose (bool disposing) foreach (var pair in inflightRequests) { pair.Key?.Cancel (); pair.Key?.Dispose (); - pair.Value?.Dispose (); } inflightRequests.Clear (); @@ -1130,7 +1128,7 @@ static bool TryGetAuthenticationType (NSUrlProtectionSpace protectionSpace, [Not } } - class InflightData : IDisposable { + class InflightData { public readonly object Lock = new object (); public string RequestUrl { get; set; } @@ -1154,21 +1152,6 @@ public InflightData (string requestUrl, CancellationToken cancellationToken, Htt CancellationToken = cancellationToken; Request = request; } - - public void Dispose () - { - Dispose (true); - GC.SuppressFinalize (this); - } - - // The bulk of the clean-up code is implemented in Dispose(bool) - protected virtual void Dispose (bool disposing) - { - if (disposing) { - CancellationTokenSource.Dispose (); - } - } - } class NSUrlSessionDataTaskStreamContent : MonoStreamContent {