Mar*_*ter 9 wpf wcf asynchronous
(假设一个名为"MyFunction"的WCF方法)
目前,为了支持取消WCF请求,我使用svcutil生成的BeginMyFunction/EndMyFunction方法(并在将结果分派给主线程时处理isCanceled标志).我想使用MyFunctionAsync方法(并挂钩到MyFunctionAsyncCompleted事件)来进行异步调用而不是Begin/End.
如果使用MyFunctionAsyncCompleted,处理取消WCF请求的最佳/支持方式是什么,并且仍然确保不会在不再加载的页面上触发事件(即帧内的页面导航).
谢谢!
编辑:
我已经决定要在每次调用的基础上创建我的WcfClient对象(而不是每个WPF-Page或per-Application),所以这就是我想出来的:
public void StartValidation(){
WcfClient wcf = new WcfClient();
wcf.IsValidCompleted += new EventHandler<IsValidCompletedEventArgs>(wcf_IsValidCompleted);
//pass the WcfClient object as the userState parameter so it can be closed later
wcf.IsValidAsync(TextBox.Text, wcf);
}
void wcf_IsValidCompleted(object sender, IsValidCompletedEventArgs e) {
if(!m_IsCanceled){
//Update the UI
//m_IsCanceled is set to true when the page unload event is fired
}
//Close the connection
if (e.UserState is WcfClient) {
((WcfClient)e.UserState).Close();
}
}
Run Code Online (Sandbox Code Playgroud)
我发现很难弄清楚我刚才实现的建议方法是什么.这是好的,还是我需要担心的陷阱/边缘情况?正确取消WCF呼叫的黄金标准是什么?
Fla*_*DOA 15
我知道使用WCF客户端和基于任务的异步模式执行此操作的最简单方法是使用取消令牌注册中止操作
private async Task CallOrAbortMyServiceAsync(CancellationToken cancellation)
{
var client = new SomeServiceClient();
cancellation.Register(() => client.Abort());
try
{
await client.CallMyServiceAsync();
} catch (CommunicationObjectAbortedException) {
// This will be called when you are cancelled, or some other fault.
}
}
Run Code Online (Sandbox Code Playgroud)
除非您手动创建异步函数,否则无法取消异步请求.考虑到你是自动生成你的WCF调用,这将使它更多的苦差事.即便如此,就像你说电话没有取消它仍然会运行它的过程.如果您仍想要取消,则只需确保客户端/ UI忽略调用的结果.
归档时间: |
|
查看次数: |
10231 次 |
最近记录: |