2

我在 winform 中使用 wcf 代理时遇到了一些问题。这个 wcf 服务托管在 IIS 上,公开了 2 种方法,并且当我在单线程 winform 中使用它时(一次调用一个),它可以正常工作。当我在不同的线程中使用相同的代理(相同的实例或 2 个单独的实例,没关系)时出现问题,我确实收到错误:“安全句柄已关闭”。

我真正不明白的是:如果我启动一些都调用相同的 wcf 方法的线程,它工作正常。仅当我开始调用其中一个 wcf 方法,开始另一个调用第二个 wcf 方法并且第二个调用在第一个调用完成之前完成时,才会出现此问题。澄清:

This will work:
    - start threadA that calls wcf MethodA
    - start threadB that calls wcf MethodA
    - MethodA in threadA finishes <-- No errors
    - MethodA in threadB finishes <-- No errors

This won't work:
    - start threadA that calls wcf MethodA
    - start threadB that calls wcf MethodB
    - MethodB in threadB finishes <-- No errors
    - MethodA in threadA finishes <-- Error "Safe handle has been closed"

This won't work either, methods order doesn't matter, only the fact that I mix methods it seems:
    - start threadA that calls wcf MethodB
    - start threadB that calls wcf MethodA
    - MethodA in threadB finishes <-- No errors
    - MethodB in threadA finishes <-- Error "Safe handle has been closed"

这是我收到的堆栈:

Server stack trace:
   at System.ServiceModel.Channels.ServiceChannel.ThrowIfFaultUnderstood(Message reply, MessageFault fault, String action, MessageVersion version, FaultConverter faultConverter)
   at System.ServiceModel.Channels.ServiceChannel.HandleReply(ProxyOperationRuntime operation, ProxyRpc& rpc)
   at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
   at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
   at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)

Exception rethrown at [0]: 
   at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
   at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
   at MyProxy.MyInterface.MyMethod(String myParam)

有人有解释吗?

4

1 回答 1

0

通常,所有代理类都派生自 System.ServiceModel.ClientBase。根据 MSDN 文档,ClientBase 的实例方法不是线程安全的。

http://msdn.microsoft.com/en-us/library/ms576141.aspx

此外,查看错误,您的服务中可能存在一些公共资源。请检查 MethodA 和 MethodB 是否正在访问公共资源。调试服务将有所帮助

于 2013-02-27T15:07:06.820 回答