Bug 30333 - Xamarin.Insights locks the main thread after several activity navigations.
Summary: Xamarin.Insights locks the main thread after several activity navigations.
Status: VERIFIED FIXED
Alias: None
Product: Android
Classification: Xamarin
Component: General ()
Version: 5.2
Hardware: PC Mac OS
: Normal normal
Target Milestone: ---
Assignee: Gord Allott
URL:
Depends on:
Blocks:
 
Reported: 2015-05-21 23:37 UTC by Matthew Robbins
Modified: 2015-08-25 07:57 UTC (History)
7 users (show)

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

Notice (2018-05-24): bugzilla.xamarin.com is now in read-only mode.

Please join us on Visual Studio Developer Community and in the Xamarin and Mono organizations on GitHub to continue tracking issues. Bugzilla will remain available for reference in read-only mode. We will continue to work on open Bugzilla bugs, copy them to the new locations as needed for follow-up, and add the new items under Related Links.

Our sincere thanks to everyone who has contributed on this bug tracker over the years. Thanks also for your understanding as we make these adjustments and improvements for the future.


Please create a new report on Developer Community or GitHub with your current version information, steps to reproduce, and relevant error messages or log files if you are hitting an issue that looks similar to this resolved bug and you do not yet see a matching new report.

Related Links:
Status:
VERIFIED FIXED

Description Matthew Robbins 2015-05-21 23:37:02 UTC
When using Xamarin.Insights within an android application, frequent navigation through activities causes the UI to lockup. This occurs in Xamarin.Insights version 1.10.2.110 and earlier. 

To reproduce, use the following code sample:

	[Activity (Label = "InsightsWaitLockBug", MainLauncher = true, Icon = "@drawable/icon")]
	public class MainActivity : Activity
	{
		string key = "insert_key_here";

		static bool isInited;

		protected override void OnCreate (Bundle bundle)
		{
			base.OnCreate (bundle);

			SetupAnalytics ();

			// Set our view from the "main" layout resource
			SetContentView (Resource.Layout.Main);

			// Get our button from the layout resource,
			// and attach an event to it
			Button button = FindViewById<Button> (Resource.Id.myButton);
			
			button.Click += delegate {
				StartActivity(typeof(MainActivity));
			};
		}

		void SetupAnalytics ()
		{
			if (!isInited) {
				Insights.Initialize (key, Application.Context);
				isInited = true;
			}
		}
	}

The above snippet is a trivialised example of the bug, it may take a few advances and retreats in the activity stack for it to be triggered.

This is a capture of the call-stack when the application is in a "frozen" state (Insights version 1.10.2.109):

System.Threading.Monitor.Monitor_wait () in 
System.Threading.Monitor.Wait (obj={object}, millisecondsTimeout=-1) in 
System.Threading.ManualResetEventSlim.Wait (millisecondsTimeout=-1, cancellationToken=The vm is not suspended.) in 
System.Threading.Tasks.Task.SpinThenBlockingWait (millisecondsTimeout=-1, cancellationToken=The vm is not suspended.) in 
System.Threading.Tasks.Task.InternalWait (millisecondsTimeout=-1, cancellationToken=The vm is not suspended.) in 
System.Threading.Tasks.Task.Wait (millisecondsTimeout=-1, cancellationToken=The vm is not suspended.) in 
System.Threading.Tasks.Task.Wait () in 
Xamarin.InsightsCore.Core.OnTerminating () in 
Xamarin.InsightsCore.Core.<SetupPlatformServices>b__3 (source={Xamarin.InsightsCore.PlatformServices}, args={System.EventArgs}) in 
Xamarin.InsightsCore.PlatformServices.OnBackgroundManagerTerminating (sender={Xamarin.InsightsCore.BackgroundManager}, args={System.EventArgs}) in 
Xamarin.InsightsCore.BackgroundManager.OnActivityDestroyed (activity={WellSite.UIL.CrudeHaulingActivity}) in 
Android.App.Application.IActivityLifecycleCallbacksInvoker.n_OnActivityDestroyed_Landroid_app_Activity_ (jnienv=0xffffffffb5051240, native__this=0xffffffffbe982b6c, native_activity=0xffffffffbe982b70) in /Users/builder/data/lanes/1502/24855232/source/monodroid/src/Mono.Android/platforms/android-19/src/generated/Android.App.Application.cs:170
object.cd2b899f-4daf-4e7b-a6fd-27fcd25c3a03 (arg0=Value not available, arg1=Value not available, arg2=Value not available) in 

The culprit is a ManualResetEvent that is locking the UI thread indirectly. Insights appears to register a IActivityLifecycleCallbacks listener in the owning application and detects the activity lifecycle events in order to log them to the Insights web-server. However, when Insights is logging multiple events at the same time, it appears to reach a limit in the amount of  worker threads it can use. Insights then uses a ManualResetEvent.Wait to lock the calling thread and wait for an available worker to dispatch the task.

This is an issue as implementations of IActivityLifecycleCallbacks receive the event dispatches on the main UI thread. Locking the main UI thread for what can be a few seconds is a serious usability issue for our application. Other applications will also be affected by this.

This question on stack overflow demonstrates the relationship between IActivityLifecycleCallbacks and the UI thread:
http://stackoverflow.com/questions/30387135/are-android-app-application-activity-life-cycle-callbacks-invoked-on-the-ui-thre

The desired behaviour is that Xamarin.Insights does not lock the main thread for long periods of time when it has run out of worker threads to handle event logs.
Comment 1 Matthew Robbins 2015-05-21 23:44:38 UTC
Version information:

=== Xamarin Studio ===

Version 5.9.2 (build 2)
Installation UUID: 38b45b60-5090-4975-819c-5617d24a7d86
Runtime:
	Mono 4.0.1 ((detached/11b5830)
	GTK+ 2.24.23 (Raleigh theme)

	Package version: 400010043

=== Apple Developer Tools ===

Xcode 5.1.1 (5085)
Build 5B1008

=== Xamarin.iOS ===

Version: 8.10.1.59 (Starter Edition)
Hash: 13d1cdc
Branch: master
Build date: 2015-05-18 22:54:57-0400

=== Xamarin.Android ===

Version: 5.1.2.0 (Business Edition)
Android SDK: /Users/matthewrobbins/Library/Developer/Xamarin/android-sdk-macosx
	Supported Android versions:
		2.3    (API level 10)
		4.0.3  (API level 15)
		4.1    (API level 16)
		4.2    (API level 17)
		4.3    (API level 18)
		4.4    (API level 19)
		4.4.87 (API level 20)
		5.0    (API level 21)
Java SDK: /usr
java version "1.7.0_71"
Java(TM) SE Runtime Environment (build 1.7.0_71-b14)
Java HotSpot(TM) 64-Bit Server VM (build 24.71-b01, mixed mode)

=== Xamarin Android Player ===

Version: Unknown version
Location: /Applications/Xamarin Android Player.app

=== Xamarin.Mac ===

Version: 2.0.1.59 (Starter Edition)

=== Build Information ===

Release ID: 509020002
Git revision: 43735a4b905b571f69cf9428a3ea7b52aef55476
Build date: 2015-05-18 09:38:12-04
Xamarin addins: ab18ddff45f507ed74f36c2b65df9aee22e28a56

=== Operating System ===

Mac OS X 10.10.3
Darwin TS-MacBook-Pro.local 14.3.0 Darwin Kernel Version 14.3.0
    Mon Mar 23 11:59:05 PDT 2015
    root:xnu-2782.20.48~5/RELEASE_X86_64 x86_64
Comment 2 Matthew Robbins 2015-05-24 20:03:58 UTC
Some more information:

I've cracked open the Xamarin.Insights assembly and found the offending call. The class Xamarin.InsightsCore.Core contains a method named OnTerminating which has a indefinite Wait() invoked on a task:

    private void OnTerminating()
    {
      if (this.DoChecks())
        return;
      try
      {
        this.Track("X-App-State", "status", "Terminated");
        this.WebApi.Save().Wait();
      }
      catch (Exception ex)
      {
        Device.PlatformServices.EmitInternalException(ex, false);
      }
      this.GetLatestJournalAndQueueCommunication(0);
    }
Comment 3 Matthew Robbins 2015-05-24 21:05:03 UTC
The hardware this bug was reproduced on:

Nexus 7.

Model number 7.

Android version 5.0.2

Kernel Version: 3.4.0-g154bef4
android-build@vpdbs1.mtv.corp.google.com #1
Thu Nov 20 22:16:47 UTC 2014

Build number: LRX22G
Comment 4 Matthew Robbins 2015-05-31 21:39:56 UTC
Is there any movement on this issue? I've done testing on another one of our applications and confirmed that Insights has caused performance degradation.
Comment 5 Neil Jagdish Patel 2015-06-01 17:20:09 UTC
Hi Matthew, thanks for the investigation into this. We think we've landed on a fix for the issue and are in the middle of running it through our test suites to make sure there are no regressions before making it public.

I should have a nuget ready tomorrow that you can test too, once our latest build publishes. We hope to get a bug fix release out in the next couple of days (with some other fixes too).
Comment 6 Matthew Robbins 2015-06-16 21:59:23 UTC
I've noticed that the latest version of Insights has been bumped to 1.10.4.112. Is a fix incoming in this or a near-future version?
Comment 7 Matthew Robbins 2015-06-16 22:13:08 UTC
Thread locking behaviour is no longer visible in:

- My testing application.
- Our Xamarin.Android application.
- Our MVVM cross based Xamarin.Android application.

Neil, can we mark this as resolved so the other watchers of this issue know it's safe to update?
Comment 8 Parmendra Kumar 2015-08-25 07:08:41 UTC
As per comment #7, mark as resolved fixed.