Skip to content

Commit

Permalink
Add a Semaphore for AttachAndRun (#7269)
Browse files Browse the repository at this point in the history
  • Loading branch information
PureWeen committed May 17, 2022
1 parent f1afbd2 commit c6317a8
Showing 1 changed file with 10 additions and 2 deletions.
12 changes: 10 additions & 2 deletions src/TestUtils/src/DeviceTests/AssertionExtensions.Android.cs
Expand Up @@ -95,6 +95,10 @@ public static AColor ColorAtPoint(this Bitmap bitmap, int x, int y, bool include
return true;
});

// Android doesn't handle adding and removing views in parallel very well
// If a view is removed while a different test triggers a layout then you hit
// a NRE exception
static SemaphoreSlim _attachAndRunSemaphore = new SemaphoreSlim(1);
public static async Task<T> AttachAndRun<T>(this AView view, Func<Task<T>> action)
{
if (view.Parent is WrapperView wrapper)
Expand All @@ -115,17 +119,21 @@ public static async Task<T> AttachAndRun<T>(this AView view, Func<Task<T>> actio
var act = context.GetActivity()!;
var rootView = act.FindViewById<FrameLayout>(Android.Resource.Id.Content)!;

layout.AddView(view);
rootView.AddView(layout);
view.Id = AView.GenerateViewId();
layout.Id = AView.GenerateViewId();

try
{
await _attachAndRunSemaphore.WaitAsync();
layout.AddView(view);
rootView.AddView(layout);
return await Run(view, action);
}
finally
{
rootView.RemoveView(layout);
layout.RemoveView(view);
_attachAndRunSemaphore.Release();
}
}
else
Expand Down

0 comments on commit c6317a8

Please sign in to comment.