/
DispatcherExtensions.cs
68 lines (60 loc) · 1.45 KB
/
DispatcherExtensions.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
60
61
62
63
64
65
66
67
68
using System;
namespace Xamarin.Forms
{
internal static class DispatcherExtensions
{
static IDispatcherProvider s_current;
static IDispatcher s_default;
public static IDispatcher GetDispatcher(this BindableObject bindableObject)
{
if (s_default != null)
{
// If we're already using the fallback dispatcher, keep using it
return s_default;
}
// See if the current platform has a DispatcherProvider for us
s_current = s_current ?? DependencyService.Get<IDispatcherProvider>();
if (s_current == null)
{
// No DispatcherProvider available, use the fallback dispatcher
s_default = new FallbackDispatcher();
return s_default;
}
// Use the DispatcherProvider to retrieve an appropriate dispatcher for this BindableObject
return s_current.GetDispatcher(bindableObject) ?? new FallbackDispatcher();
}
public static void Dispatch(this IDispatcher dispatcher, Action action)
{
if (dispatcher != null)
{
if (dispatcher.IsInvokeRequired)
{
dispatcher.BeginInvokeOnMainThread(action);
}
else
{
action();
}
}
else
{
if (Device.IsInvokeRequired)
{
Device.BeginInvokeOnMainThread(action);
}
else
{
action();
}
}
}
}
internal class FallbackDispatcher : IDispatcher
{
public bool IsInvokeRequired => Device.IsInvokeRequired;
public void BeginInvokeOnMainThread(Action action)
{
Device.BeginInvokeOnMainThread(action);
}
}
}