Portable class library equivalent of Dispatcher.Invoke or Dispatcher.RunAsync

前端 未结 2 1959
梦谈多话
梦谈多话 2020-12-14 12:12

In .NET, Windows 8 and Windows Phone 7 I have code similar to this:

public static void InvokeIfRequired(this Dispatcher dispatcher, Action action)
{
    if (         


        
相关标签:
2条回答
  • 2020-12-14 12:38

    You can use SynchronizationContext.Post or Send method. It is portable, and when you use a UI framework with a dispatcher then the current synchronization context will delegate the work to the Dispatcher.

    Specifically, you can use the following code:

    void InvokeIfRequired(this SynchroniationContext context, Action action)
    {
        if (SynchroniationContext.Current == context)
        {
            action();
        }
        else
        {
            context.Send(action) // send = synchronously
            // context.Post(action)  - post is asynchronous.
        }  
    }
    
    0 讨论(0)
  • 2020-12-14 12:40

    With the advent of the TPL. I came up with a slightly improved version of the accepted answer which returns a task and can be await'ed using the new async and await keywords.

    public Task RunAsync(Action action)
    {
        TaskCompletionSource<object> taskCompletionSource = new TaskCompletionSource<object>();
    
        if (this.synchronizationContext == SynchronizationContext.Current)
        {
            try
            {
                action();
                taskCompletionSource.SetResult(null);
            }
            catch (Exception exception)
            {
                taskCompletionSource.SetException(exception);
            }
        }
        else
        {
            // Run the action asyncronously. The Send method can be used to run syncronously.
            this.synchronizationContext.Post(
                (obj) => 
                {
                    try
                    {
                        action();
                        taskCompletionSource.SetResult(null);
                    }
                    catch (Exception exception)
                    {
                        taskCompletionSource.SetException(exception);
                    }
                }, 
                null);
        }
    
        return taskCompletionSource.Task;
    }
    
    0 讨论(0)
提交回复
热议问题