This is Xamarin's bug tracking system. For product support, please use the support links listed in your Xamarin Account.
Bug 44961 - AndroidClientHandler throws NetworkOnMainThreadException
Summary: AndroidClientHandler throws NetworkOnMainThreadException
Status: RESOLVED FIXED
Alias: None
Product: Android
Classification: Xamarin
Component: Mono runtime / AOT Compiler (show other bugs)
Version: unspecified
Hardware: PC Windows
: --- normal
Target Milestone: ---
Assignee: Marek Habersack
URL:
Depends on:
Blocks:
 
Reported: 2016-10-01 04:12 UTC by cschulte
Modified: 2016-10-06 22:44 UTC (History)
2 users (show)

See Also:
Tags:
Is this bug a regression?: ---
Last known good build:


Attachments

Description cschulte 2016-10-01 04:12:17 UTC
AndroidClientHandler sometimes throws NetworkOnMainThreadException.  This problem doesn't always occur but I observed it on the Android emulators.  I guess it depends on the underlying HttpUrlConnection implementation which probably varies between devices / OS versions?

Anyways, here's the line that can throw the exception (line 254 inside HttpClientHandler.cs):

    var statusCode = (HttpStatusCode)httpConnection.ResponseCode;

You need to wrap it in a task to prevent the NetworkOnMainThreadException from being thrown:

    var statusCode = await Task.Run(() => (HttpStatusCode)httpConnection.ResponseCode);



I created my own sub-class to workaround this problem:

    public class AndroidClientHandler : global::Xamarin.Android.Net.AndroidClientHandler
    {
        protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            //Wrap it in a task, work around for run on ui thread bug
            return await Task.Run(() => base.SendAsync(request, cancellationToken));
        }
    }
Comment 1 Marek Habersack 2016-10-03 11:05:55 UTC
PR with the fix created: https://github.com/xamarin/xamarin-android/pull/247
Comment 2 Marek Habersack 2016-10-03 18:43:05 UTC
And it's fixed in monodroid/master, commit 2c02bcf1f4e002941c3beca661075da5cc1ac087
Comment 3 Marek Habersack 2016-10-03 18:44:30 UTC
Correction, it's xamarin-android/master, commit 2c02bcf1f4e002941c3beca661075da5cc1ac087
Comment 4 Marek Habersack 2016-10-03 19:54:19 UTC
Fix included in monodroid/master, commit 3aae2ff34d7ae746d53310fb5bc73d40b2908aaa

Note You need to log in before you can comment on or make changes to this bug.