44
55using System ;
66using System . Threading . Tasks ;
7+ using Windows . Foundation . Metadata ;
78using Windows . System ;
89
910#nullable enable
@@ -15,6 +16,11 @@ namespace Microsoft.Toolkit.Uwp.Extensions
1516 /// </summary>
1617 public static class DispatcherQueueExtensions
1718 {
19+ /// <summary>
20+ /// Indicates whether or not <see cref="DispatcherQueue.HasThreadAccess"/> is available.
21+ /// </summary>
22+ private static readonly bool IsHasThreadAccessPropertyAvailable = ApiInformation . IsMethodPresent ( "Windows.System.DispatcherQueue" , "HasThreadAccess" ) ;
23+
1824 /// <summary>
1925 /// Invokes a given function on the target <see cref="DispatcherQueue"/> and returns a
2026 /// <see cref="Task"/> that completes when the invocation of the function is completed.
@@ -29,7 +35,7 @@ public static Task EnqueueAsync(this DispatcherQueue dispatcher, Action function
2935 // Run the function directly when we have thread access.
3036 // Also reuse Task.CompletedTask in case of success,
3137 // to skip an unnecessary heap allocation for every invocation.
32- if ( dispatcher . HasThreadAccess )
38+ if ( IsHasThreadAccessPropertyAvailable && dispatcher . HasThreadAccess )
3339 {
3440 try
3541 {
@@ -82,7 +88,7 @@ static Task TryEnqueueAsync(DispatcherQueue dispatcher, Action function, Dispatc
8288 /// <remarks>If the current thread has access to <paramref name="dispatcher"/>, <paramref name="function"/> will be invoked directly.</remarks>
8389 public static Task < T > EnqueueAsync < T > ( this DispatcherQueue dispatcher , Func < T > function , DispatcherQueuePriority priority = DispatcherQueuePriority . Normal )
8490 {
85- if ( dispatcher . HasThreadAccess )
91+ if ( IsHasThreadAccessPropertyAvailable && dispatcher . HasThreadAccess )
8692 {
8793 try
8894 {
@@ -134,7 +140,7 @@ public static Task EnqueueAsync(this DispatcherQueue dispatcher, Func<Task> func
134140 // We don't use ConfigureAwait(false) in this case, in order
135141 // to let the caller continue its execution on the same thread
136142 // after awaiting the task returned by this function.
137- if ( dispatcher . HasThreadAccess )
143+ if ( IsHasThreadAccessPropertyAvailable && dispatcher . HasThreadAccess )
138144 {
139145 try
140146 {
@@ -197,7 +203,7 @@ static Task TryEnqueueAsync(DispatcherQueue dispatcher, Func<Task> function, Dis
197203 /// <remarks>If the current thread has access to <paramref name="dispatcher"/>, <paramref name="function"/> will be invoked directly.</remarks>
198204 public static Task < T > EnqueueAsync < T > ( this DispatcherQueue dispatcher , Func < Task < T > > function , DispatcherQueuePriority priority = DispatcherQueuePriority . Normal )
199205 {
200- if ( dispatcher . HasThreadAccess )
206+ if ( IsHasThreadAccessPropertyAvailable && dispatcher . HasThreadAccess )
201207 {
202208 try
203209 {
0 commit comments