android: Application crash from finalizer in AndroidHttpHandler when disposing

I appears to me that the AndroidClientHandler does not appreciate being disposed while a request is in progress / getting cancelled. This can lead to application crashes.

Steps to Reproduce

Run the following code and see the unobserved task exception is hit (even though it’s being observed in the continuation method:

        private async void TestRequests()
        {
            TaskScheduler.UnobservedTaskException += (object sender, UnobservedTaskExceptionEventArgs args) =>
            {
                // App will crash here if we don't handle it
                args.SetObserved();
                Debugger.Break();
            };
            for (int i = 0; i < 100; i++)
            {
                //using (var handler = new System.Net.Http.HttpClientHandler()) // Doesn't crash
                using (var handler = new AndroidClientHandler()) 
                {
                    using (HttpClient client = new HttpClient(handler))
                    {
                        using (var request = new HttpRequestMessage(HttpMethod.Get, "http://sampleserver3.arcgisonline.com/ArcGIS/rest/services/Earthquakes/EarthquakesFromLastSevenDays/MapServer/0/query?text=&geometry=&geometryType=esriGeometryPoint&inSR=&spatialRel=esriSpatialRelIntersects&relationParam=&objectIds=&where=1%3D1&time=&returnCountOnly=false&returnIdsOnly=false&returnGeometry=true&maxAllowableOffset=&outSR=&outFields=&f=pjson&t=" + DateTime.Now.Ticks.ToString()))
                        {
                            CancellationTokenSource tcs = new CancellationTokenSource();
                            tcs.CancelAfter(100);
                            try
                            {
                                _ = client.SendAsync(request, tcs.Token).ContinueWith(t =>
                                {
                                });
                            }
                            catch { }
                        }
                    }
                }
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
        }

This’ll throw

A Task’s exception(s) were not observed either by Waiting on the Task or accessing its Exception property. As a result, the unobserved exception was rethrown by the finalizer thread. (Cannot access a disposed object. Object name: ‘AndroidClientHandler’.) StackTrace

  at System.Threading.Tasks.Task.InnerInvoke () [0x0000f] in /Users/builder/jenkins/workspace/archive-mono/2019-10/android/release/external/corert/src/System.Private.CoreLib/src/System/Threading/Tasks/Task.cs:2476 
  at System.Threading.Tasks.Task.Execute () [0x00000] in /Users/builder/jenkins/workspace/archive-mono/2019-10/android/release/external/corert/src/System.Private.CoreLib/src/System/Threading/Tasks/Task.cs:2319 
--- End of stack trace from previous location where exception was thrown ---

  at Xamarin.Android.Net.AndroidClientHandler.SetupRequestInternal (System.Net.Http.HttpRequestMessage request, Java.Net.URLConnection conn) [0x0020f] in <4ccdb3137d974856b786e1aeebbfbab6>:0 
  at Xamarin.Android.Net.AndroidClientHandler.SendAsync (System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) [0x00247] in <4ccdb3137d974856b786e1aeebbfbab6>:0 
  at System.Net.Http.HttpClient.FinishSendAsyncBuffered (System.Threading.Tasks.Task`1[TResult] sendTask, System.Net.Http.HttpRequestMessage request, System.Threading.CancellationTokenSource cts, System.Boolean disposeCts) [0x0017e] in /Users/builder/jenkins/workspace/archive-mono/2019-10/android/release/external/corefx/src/System.Net.Http/src/System/Net/Http/HttpClient.cs:506 

In my specific scenario I’m seeing an exception being thrown in the StatusCode getter:

A Task’s exception(s) were not observed either by Waiting on the Task or accessing its Exception property. As a result, the unobserved exception was rethrown by the finalizer thread. (Canceled) Inner Exception Java.IO.IOException: Canceled StackTrace:

    at Java.Interop.JniEnvironment+InstanceMethods.CallIntMethod (Java.Interop.JniObjectReference instance, Java.Interop.JniMethodInfo method, Java.Interop.JniArgumentValue* args) [0x0006e] in <26521a5118b44c858c385715922b9d5d>:0 
    at Java.Interop.JniPeerMembers+JniInstanceMethods.InvokeVirtualInt32Method (System.String encodedMember, Java.Interop.IJavaPeerable self, Java.Interop.JniArgumentValue* parameters) [0x0002a] in <26521a5118b44c858c385715922b9d5d>:0 
    at Java.Net.HttpURLConnection.get_ResponseCode () [0x00000] in /Users/runner/runners/2.165.0/work/1/s/xamarin-android/src/Mono.Android/obj/Release/android-28/mcw/Java.Net.HttpURLConnection.cs:505 
    at Xamarin.Android.Net.AndroidClientHandler+<>c__DisplayClass46_0.<DoProcessRequest>b__2 () [0x00000] in /Users/runner/runners/2.165.0/work/1/s/xamarin-android/src/Mono.Android/Xamarin.Android.Net/AndroidClientHandler.cs:426 
    at System.Threading.Tasks.Task`1[TResult].InnerInvoke () [0x0000f] in /Users/builder/jenkins/workspace/archive-mono/2019-10/android/release/external/corert/src/System.Private.CoreLib/src/System/Threading/Tasks/Future.cs:534 
    at System.Threading.Tasks.Task.Execute () [0x00000] in /Users/builder/jenkins/workspace/archive-mono/2019-10/android/release/external/corert/src/System.Private.CoreLib/src/System/Threading/Tasks/Task.cs:2319 
  --- End of stack trace from previous location where exception was thrown ---
  
    at Xamarin.Android.Net.AndroidClientHandler.DoProcessRequest (System.Net.Http.HttpRequestMessage request, Java.Net.URL javaUrl, Java.Net.HttpURLConnection httpConnection, System.Threading.CancellationToken cancellationToken, Xamarin.Android.Net.AndroidClientHandler+RequestRedirectionState redirectState) [0x00322] in /Users/runner/runners/2.165.0/work/1/s/xamarin-android/src/Mono.Android/Xamarin.Android.Net/AndroidClientHandler.cs:426 
    at Xamarin.Android.Net.AndroidClientHandler.SendAsync (System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) [0x00285] in /Users/runner/runners/2.165.0/work/1/s/xamarin-android/src/Mono.Android/Xamarin.Android.Net/AndroidClientHandler.cs:286 

The get statuscode actually lists this as a property than can throw an IOException. The line of code is also especially suspicious as it does a Task.Run but doesn’t consider things could get disposed as that is being posted: https://github.com/xamarin/xamarin-android/blob/d48cf04f9749664bf48fc16bcb920d5d941cccab/src/Mono.Android/Xamarin.Android.Net/AndroidClientHandler.cs#L426

Expected Behavior

No crash from the finalizer

Actual Behavior

Crash 😃

Version Information

Microsoft Visual Studio Enterprise 2019 Version 16.5.3 VisualStudio.16.Release/16.5.3+30002.166 Microsoft .NET Framework Version 4.8.03752

Installed Version: Enterprise

Visual C++ 2019 00435-60000-00000-AA944 Microsoft Visual C++ 2019

ArcGIS Runtime SDK for .NET 100.7.0 ArcGIS Runtime SDK for .NET allows developers to build immersive, native mapping applications for Windows, Android, and iOS devices using C#. It includes five APIs: WPF to create apps for Windows Desktop, UWP to create Universal Windows apps, Xamarin.Android and Xamarin.iOS for Android and iOS apps that need access to native functionality, and Xamarin.Forms to create apps that share UI layouts across Android, iOS, and UWP.

ASP.NET and Web Tools 2019 16.5.236.49856 ASP.NET and Web Tools 2019

ASP.NET Web Frameworks and Tools 2019 16.5.236.49856 For additional information, visit https://www.asp.net/

Azure App Service Tools v3.0.0 16.5.236.49856 Azure App Service Tools v3.0.0

Azure Functions and Web Jobs Tools 16.5.236.49856 Azure Functions and Web Jobs Tools

C# Tools 3.5.0-beta4-20153-05+20b9af913f1b8ce0a62f72bea9e75e4aa3cf6b0e C# components used in the IDE. Depending on your project type and settings, a different version of the compiler may be used.

Common Azure Tools 1.10 Provides common services for use by Azure Mobile Services and Microsoft Azure Tools.

Extensibility Message Bus 1.2.0 (d16-2@8b56e20) Provides common messaging-based MEF services for loosely coupled Visual Studio extension components communication and integration.

IntelliCode Extension 1.0 IntelliCode Visual Studio Extension Detailed Info

Microsoft Azure Tools 2.9 Microsoft Azure Tools for Microsoft Visual Studio 2019 - v2.9.30207.1

Microsoft Continuous Delivery Tools for Visual Studio 0.4 Simplifying the configuration of Azure DevOps pipelines from within the Visual Studio IDE.

Microsoft JVM Debugger 1.0 Provides support for connecting the Visual Studio debugger to JDWP compatible Java Virtual Machines

Microsoft Library Manager 2.1.25+gdacdb9b7a1 Install client-side libraries easily to any web project

Microsoft MI-Based Debugger 1.0 Provides support for connecting Visual Studio to MI compatible debuggers

Microsoft Visual C++ Wizards 1.0 Microsoft Visual C++ Wizards

Microsoft Visual Studio Tools for Containers 1.1 Develop, run, validate your ASP.NET Core applications in the target environment. F5 your application directly into a container with debugging, or CTRL + F5 to edit & refresh your app without having to rebuild the container.

Microsoft Visual Studio VC Package 1.0 Microsoft Visual Studio VC Package

Mono Debugging for Visual Studio 16.5.514 (c4f36a9) Support for debugging Mono processes with Visual Studio.

NuGet Package Manager 5.5.0 NuGet Package Manager in Visual Studio. For more information about NuGet, visit https://docs.nuget.org/

ProjectServicesPackage Extension 1.0 ProjectServicesPackage Visual Studio Extension Detailed Info

Snapshot Debugging Extension 1.0 Snapshot Debugging Visual Studio Extension Detailed Info

SQL Server Data Tools 16.0.62003.05170 Microsoft SQL Server Data Tools

Test Adapter for Boost.Test 1.0 Enables Visual Studio’s testing tools with unit tests written for Boost.Test. The use terms and Third Party Notices are available in the extension installation directory.

Test Adapter for Google Test 1.0 Enables Visual Studio’s testing tools with unit tests written for Google Test. The use terms and Third Party Notices are available in the extension installation directory.

TypeScript Tools 16.0.20225.2001 TypeScript Tools for Microsoft Visual Studio

UnoPlatformPackage Extension 1.0 UnoPlatformPackage Visual Studio Extension Detailed Info

Visual Basic Tools 3.5.0-beta4-20153-05+20b9af913f1b8ce0a62f72bea9e75e4aa3cf6b0e Visual Basic components used in the IDE. Depending on your project type and settings, a different version of the compiler may be used.

Visual F# Tools 10.8.0.0 for F# 4.7 16.5.0-beta.20181.6+85af456066acd4e76d2bc7821b44a325e46f2fca Microsoft Visual F# Tools 10.8.0.0 for F# 4.7

Visual Studio Code Debug Adapter Host Package 1.0 Interop layer for hosting Visual Studio Code debug adapters in Visual Studio

Visual Studio Container Tools Extensions (Preview) 1.0 View, manage, and diagnose containers within Visual Studio.

Visual Studio Tools for CMake 1.0 Visual Studio Tools for CMake

Visual Studio Tools for Containers 1.0 Visual Studio Tools for Containers

VisualStudio.DeviceLog 1.0 Information about my package

VisualStudio.Foo 1.0 Information about my package

VisualStudio.Mac 1.0 Mac Extension for Visual Studio

Xamarin 16.5.000.533 (d16-5@9152e1b) Visual Studio extension to enable development for Xamarin.iOS and Xamarin.Android.

Xamarin Designer 16.5.0.470 (remotes/origin/d16-5@681de3fd6) Visual Studio extension to enable Xamarin Designer tools in Visual Studio.

Xamarin Templates 16.5.49 (0904f41) Templates for building iOS, Android, and Windows apps with Xamarin and Xamarin.Forms.

Xamarin.Android SDK 10.2.0.100 (d16-5/988c811) Xamarin.Android Reference Assemblies and MSBuild support. Mono: c0c5c78 Java.Interop: xamarin/java.interop/d16-5@fc18c54 ProGuard: xamarin/proguard/master@905836d SQLite: xamarin/sqlite/3.28.0@46204c4 Xamarin.Android Tools: xamarin/xamarin-android-tools/d16-5@9f4ed4b

Xamarin.iOS and Xamarin.Mac SDK 13.16.0.13 (b75deaf) Xamarin.iOS and Xamarin.Mac Reference Assemblies and MSBuild support.

About this issue

  • Original URL
  • State: closed
  • Created 7 years ago
  • Comments: 34 (34 by maintainers)

Commits related to this issue

Most upvoted comments

So built a repro case for the scenario that the handler doesn’t return until all data has been read so I could log an issue for it. The good news is: It does return control back to the caller once the headers have been read. So I confirmed that what you stated here isn’t true:

it will only return when either it’s aborted or after it completes the whole read.

Here’s a bit of Forms code that shows bytes downloaded as they trickle in from the network:

       public async Task DownloadFile(string url, CancellationToken cancellationToken)
        {
            try
            {
                HttpClient client = new HttpClient();

                var response = await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, cancellationToken);

                byte[] buffer = new byte[4 * 1024];
                long progress = 0;
                using (var readstream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false))
                {
                    while (true)
                    {
                        var read = await readstream.ReadAsync(buffer, 0, buffer.Length, cancellationToken).ConfigureAwait(false);
                        progress += read;
                        if (read == 0)
                            break;
                        Device.BeginInvokeOnMainThread(() =>
                        {
                            status.Text = $"{progress} bytes downloaded...";
                        });
                    }
                }
                Device.BeginInvokeOnMainThread(() =>
                {
                    status.Text = $"Completed downloading {progress} bytes";
                });

            }
            catch (OperationCanceledException)
            {
                Device.BeginInvokeOnMainThread(() =>
                {
                    status.Text = $"Download cancelled";
                });
            }
        }

I validated that this is in fact using the default AndroidClientHandler: image Also the behavior of the app completely changes if I change the HttpCompletionOption from ResponseHeadersRead to ResponseContentRead (no status update until it’s fully downloaded.

So my argument still stands: You need to be able to handle cancellation at any point during the download, which might be after this task returned, but the download is still in-progress.