Exemplo n.º 1
0
 private static Task PerformDispatcherQueueAction(DispatcherQueueHandler action)
 {
     try
     {
         action();
         return(Task.CompletedTask);
     }
     catch (Exception exc)
     {
         return(Task.FromException(exc));
     }
 }
Exemplo n.º 2
0
 private static void PerformDispatcherQueueAction(TaskCompletionSource taskCompletionSource, DispatcherQueueHandler action)
 {
     try
     {
         action();
         taskCompletionSource.SetResult();
     }
     catch (Exception exc)
     {
         taskCompletionSource.SetException(exc);
     }
 }
Exemplo n.º 3
0
    /// <summary>
    /// Runs the specified task on the thread associated with the <see cref="DispatcherQueue"/>
    /// with the specified priority asynchronously.
    /// </summary>
    /// <param name="dispatcher">The <see cref="DispatcherQueue"/> with which the thread is associated.</param>
    /// <param name="priority">The priority of the task (such as Low, Normal, or High).</param>
    /// <param name="action">The delegate to the task to execute.</param>
    /// <returns>A task that represents the asynchronous operation.</returns>
    public static Task RunAsync(this DispatcherQueue dispatcher, DispatcherQueuePriority priority, DispatcherQueueHandler action)
    {
        if (dispatcher.HasThreadAccess)
        {
            return(PerformDispatcherQueueAction(action));
        }

        var taskCompletionSource = new TaskCompletionSource();

        if (!dispatcher.TryEnqueue(priority, () => PerformDispatcherQueueAction(taskCompletionSource, action)))
        {
            taskCompletionSource.SetException(new InvalidOperationException("Failed to enqueue the task to execute."));
        }

        return(taskCompletionSource.Task);
    }
Exemplo n.º 4
0
 /// <summary>
 /// Runs the specified task on the thread associated with the <see cref="DispatcherQueue"/> asynchronously.
 /// </summary>
 /// <param name="dispatcher">The <see cref="DispatcherQueue"/> with which the thread is associated.</param>
 /// <param name="action">The delegate to the task to execute.</param>
 /// <returns>A task that represents the asynchronous operation.</returns>
 public static Task RunAsync(this DispatcherQueue dispatcher, DispatcherQueueHandler action) => RunAsync(dispatcher, DispatcherQueuePriority.Normal, action);