[英]How to close Client Proxy with Async Call WCF
我有一个WCF客户端代理,可用来调用如下异步方法:
var prox = new DoSomethingServiceClient("BasicHttpBinding_IDoSomethingService");
prox.DoSomethingCompleted += new EventHandler<AsyncCompletedEventArgs>(svcref_DoSomethingCompleted);
prox.DoSomethingAsync(0, Guid.NewGuid());
我什么时候关闭/中止代理?
我svcref_DoSomethingCompleted
使用发件人对象在svcref_DoSomethingCompleted
中的第一行中svcref_DoSomethingCompleted
操作?
我在MS文档中看到它们关闭了主线程中的代理,而不是回调中的代理。 那是好习惯吗? 我觉得不对:
http://msdn.microsoft.com/en-us/library/ms730059(v=vs.110).aspx
我还发现了这一点,它使用基于任务的异步方式,建议您在委托回调中关闭代理,这是我所期望的:
http://fun-with-blackhawk.blogspot.com/2010/03/wcf-exception-handling-in-asynchronous.html
这就是WCF变得棘手的地方。 当服务器调用回调方法时,它需要在关闭客户端代理之前完成该调用。 这意味着要往返于客户和客户之间。 Microsoft示例向客户端(通过Console.ReadLine())请求用户输入以触发关闭。 如果要使用异步回调触发关闭,则需要发挥创意。 例如,您可以将关闭队列放在新线程上,然后延迟执行。 这将允许回调完成返回服务器的行程,然后关闭通道。
在回调中添加以下内容:
var currentChannel = OperationContext.Current.Channel;
ThreadPool.QueueUserWorkItem(o => CloseChannel(currentChannel));
然后针对CloseChannel:
private static void CloseChannel<T>(T channel)
{
var clientChannel = (IClientChannel)channel;
var success = false;
try
{
//sleep before close so the main thread has a chance to catch up
Thread.Sleep(10000);
clientChannel.Close();
success = true;
}
catch (CommunicationException ce)
{
clientChannel.Abort();
}
catch (TimeoutException te)
{
clientChannel.Abort();
}
finally
{
if (!success)
clientChannel.Abort();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.