forked from dotnet/android
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SyncContext.cs
59 lines (51 loc) · 1.45 KB
/
SyncContext.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using Android.OS;
using Android.Runtime;
namespace Android.App {
internal class SyncContext : SynchronizationContext {
public override SynchronizationContext CreateCopy ()
{
return new SyncContext ();
}
static bool EnsureLooper ([NotNullWhen (true)]Looper? looper, SendOrPostCallback d)
{
if (looper == null) {
var message = $"No Android message loop is available. Skipping invocation of `{d.Method.DeclaringType?.FullName}.{d.Method.Name}`!";
if (JNIEnvInit.IsRunningOnDesktop)
message += " Using `await` when running on the Android Designer is not currently supported. Please use the `View.IsInEditMode` property.";
Logger.Log (LogLevel.Error, "monodroid-synccontext", message);
return false;
}
return true;
}
public override void Post (SendOrPostCallback d, object state)
{
var looper = Application.Context?.MainLooper;
if (!EnsureLooper (looper, d))
return;
using (var h = new Handler (looper)) {
h.Post (() => d (state));
}
}
public override void Send (SendOrPostCallback d, object state)
{
var looper = Looper.MainLooper;
if (!EnsureLooper (looper, d))
return;
if (Looper.MyLooper() == looper) {
d (state);
return;
}
var m = new ManualResetEvent (false);
using (var h = new Handler (looper)) {
h.Post (() => {
d (state);
m.Set ();
});
}
m.WaitOne ();
}
}
}