Skip to content

Commit 9e28681

Browse files
[One .NET] call SynchronizationContext.SetSynchronizationContext() on startup (#5243)
Fixes: #4655 The following test is failing under .NET 5+ because `SynchronizationContext.Current` returns `null`: [Test] public void SynchronizationContext_Is_ThreadingSynchronizationContextCurrent () { bool same = false; Application.SynchronizationContext.Send (_ => { var c = System.Threading.SynchronizationContext.Current; same = object.ReferenceEquals (c, Application.SynchronizationContext); }, null); Assert.IsTrue (same); } Following how this works in current Xamarin.Android / Mono: * https://github.com/mono/mono/blob/169a842f4e913608b17a1e5f38bcb635063b8dc8/mcs/class/referencesource/mscorlib/system/threading/synchronizationcontext.cs#L297 * https://github.com/mono/mono/blob/d6f0c25d34da7512639346828ef368ff65a25003/mcs/class/corlib/System/AndroidPlatform.cs#L37-L53 * https://github.com/xamarin/xamarin-android/blob/master/src/Mono.Android/Android.Runtime/AndroidEnvironment.cs#L289-L302 dotnet/runtime won't make the call to `AndroidEvironment.GetDefaultSyncContext()`, as the same pattern is not in place for other platforms. The suggested alternative is to call `SynchronizationContext.SetSynchronizationContext()` on startup. We should be able to call `Application.SynchronizationContext` directly to do this. After these changes, the original code example works as expected: Application.SynchronizationContext.Send (_ => { var c = System.Threading.SynchronizationContext.Current; button.Text += " 1:" + c?.ToString(); var same = object.ReferenceEquals (c, Application.SynchronizationContext); button.Text += " 2:" + Application.SynchronizationContext?.ToString(); button.Text += " 3:" + same; }, null);
1 parent 68be8d8 commit 9e28681

File tree

1 file changed

+4
-0
lines changed

1 file changed

+4
-0
lines changed

src/Mono.Android/Android.Runtime/JNIEnv.cs

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -192,6 +192,10 @@ internal static unsafe void Initialize (JnienvInitializeArgs* args)
192192
}
193193
}
194194

195+
#if !MONOANDROID1_0
196+
SynchronizationContext.SetSynchronizationContext (Android.App.Application.SynchronizationContext);
197+
#endif
198+
195199
if (logTiming) {
196200
monodroid_timing_stop (total_timing_sequence, "JNIEnv.Initialize end");
197201
}

0 commit comments

Comments
 (0)