WPF/WCF Async Service Call and SynchronizationContext

天涯浪子 提交于 2020-01-16 19:25:10

问题


I have a feeling there's got to be a better solution than what I've come up with; here's the problem:

A WPF form will call a WCF method, which returns a bool. The call itself should not be on the UI thread, and the result of the call will need to be displayed on the form, so the return should be marshaled back on to the UI thread.

In this example I created a "ServiceGateway" class, to which the form will pass a method to be executed upon completion of a Login operation. The gateway should invoke this Login-complete delegate using the UI SynchronizationContext, which is passed upon instantiation of the gateway from the form. The Login method invokes a call to _proxy.Login using an anon. async delegate, and then provides a callback which invokes the delegate ('callback' param) provided to the gateway (from the form) using the UI SynchronizationContext:

[CallbackBehavior(UseSynchronizationContext = false)]
public class ChatServiceGateway : MessagingServiceCallback
{

    private MessagingServiceClient _proxy;
    private SynchronizationContext _uiSyncContext;

    public ChatServiceGateway(SynchronizationContext UISyncContext)
    {
        _proxy = new MessagingServiceClient(new InstanceContext(this));
        _proxy.Open();
        _uiSyncContext = UISyncContext;
    }


    public void Login(String UserName, Action<bool> callback)
    {
        new Func<bool>(() => _proxy.Login(UserName)).BeginInvoke(delegate(IAsyncResult result)
        {
            bool LoginResult = ((Func<bool>)((AsyncResult)result).AsyncDelegate).EndInvoke(result);
            _uiSyncContext.Send(new SendOrPostCallback(obj => callback(LoginResult)), null);
        }, null);

    }

The Login method is called from the form in response to a button click event.

This works fine, but I have a suspicion I'm going about the Login method the wrong way; especially because I'll have to do the same for any other method call to the WCF service, and its ugly.

I would like to keep the async behavior and ui synchronization encapsulated in the gateway. Would it be better to have the asynchronous behavior implemented on the WCF side? Basically I'm interested if I can implement the above code more generically for other methods, or if there's a better way all together.


回答1:


Provided that you're targeting at least VS 2012 and .NET 4.5, async/await is the way to go. Note the lack of SynchronizationContext reference - it's captured under the covers before the await, and posted back to once the async operation has completed.

public async Task Login(string userName, Action<bool> callback)
{
    // The delegate passed to `Task.Run` is executed on a ThreadPool thread.
    bool loginResult = await Task.Run(() => _proxy.Login(userName));

    // OR
    // await _proxy.LoginAsync(UserName);
    // if you have an async WCF contract.

    // The callback is executed on the thread which called Login.
    callback(loginResult);
}

Task.Run is primarily used to push CPU-bound work to the thread pool, so the example above does abuse it somewhat, but if you don't want to rewrite the contract implemented by MessagingServiceClient to use asynchronous Task-based methods, it is still a pretty good way to go.

Or the .NET 4.0 way (no async/await support):

public Task Login(string userName, Action<bool> callback)
{
    // The delegate passed to `Task.Factory.StartNew`
    // is executed on a ThreadPool thread.
    var task = Task.Factory.StartNew(() => _proxy.Login(userName));

    // The callback is executed on the thread which called Login.
    var continuation = task.ContinueWith(
        t => callback(t.Result),
        TaskScheduler.FromCurrentSynchronizationContext()
    );

    return continuation;
}

This is a bit of a departure from the way you're currently doing things in that it is the responsibility of the caller to ensure that Login is getting called on the UI thread if they want the callback to be executed on it. That is, however, standard practice when it comes to async, and while you could keep a reference to the UI SynchronizationContext or TaskScheduler as part of your ChatServiceGateway to force the callback/continuation to execute on the right thread, it will blow out your implementation and personally (and this is just my opinion) I would say that that's a bit of a code smell.



来源:https://stackoverflow.com/questions/26129182/wpf-wcf-async-service-call-and-synchronizationcontext

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!