[英]WPF/WCF Async Service Call and SynchronizationContext
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. WPF表单将调用WCF方法,该方法返回布尔值。 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.
调用本身不应位于UI线程上,并且调用结果将需要显示在表单上,因此应将返回结果编组回UI线程。
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. 在此示例中,我创建了一个“ ServiceGateway”类,该表单将向其传递一个方法,该方法将在完成Login操作后执行。 The gateway should invoke this Login-complete delegate using the UI SynchronizationContext, which is passed upon instantiation of the gateway from the form.
网关应该使用UI SynchronizationContext调用此登录完成的委托,该委托在网关从窗体实例化时传递。 The Login method invokes a call to _proxy.Login using an anon.
Login方法使用anon调用_proxy.Login的调用。 async delegate, and then provides a callback which invokes the delegate ('callback' param) provided to the gateway (from the form) using the UI SynchronizationContext:
异步委托,然后提供一个回调,该回调使用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. 响应按钮单击事件,从表单中调用Login方法。
This works fine, but I have a suspicion I'm going about the Login method the wrong way; 这可以正常工作,但是我怀疑我要以错误的方式使用Login方法。 especially because I'll have to do the same for any other method call to the WCF service, and its ugly.
尤其是因为我必须对WCF服务的其他任何方法调用做同样的事情,而且这样做很丑陋。
I would like to keep the async behavior and ui synchronization encapsulated in the gateway. 我想将异步行为和ui同步封装在网关中。 Would it be better to have the asynchronous behavior implemented on the WCF side?
在WCF端实现异步行为会更好吗? 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.
基本上,我很感兴趣是否可以为其他方法更通用地实现上述代码,或者是否有更好的方法。
Provided that you're targeting at least VS 2012 and .NET 4.5, async/await
is the way to go. 只要您的目标至少是VS 2012和.NET 4.5,
async/await
是async/await
的方法。 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. 请注意,缺少
SynchronizationContext
参考-在await
之前将其捕获,并在异步操作完成后重新发布。
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. Task.Run
主要用于将与CPU绑定的工作推送到线程池,因此上面的示例确实滥用了它,但是如果您不想重写MessagingServiceClient
实现的协定以使用基于Task
的异步方法,则可以仍然是一个不错的选择。
Or the .NET 4.0 way (no async/await
support): 或.NET 4.0方式(不支持
async/await
):
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. 这与您当前的处理方式有所不同, 因为调用者有责任确保希望在其上执行回调的情况下在UI线程上调用
Login
。 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. 但是,这是
async
标准做法,尽管您可以在ChatServiceGateway
保留对UI SynchronizationContext
或TaskScheduler
的ChatServiceGateway
以强制回调/继续在正确的线程上执行,但它会使您的实现ChatServiceGateway
就个人而言(这只是我的观点 ),我会说这有点代码味道。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.