我正在尝试构建一个WCF服务,该服务公开了我没有原始源的特定COM对象的功能。我正在使用双工绑定,以便每个客户端都有自己的实例,因为每个特定实例都绑定了通过回调(IAgent)传递的事件。似乎存在死锁或其他因素,因为在第一次操作之后,我的服务阻止了我的第二个动作的锁定。我已经尝试实现这些自定义STA属性和操作行为(http://devlicio.us/blogs/scott_seely/archive/2009/07/17/calling-an-sta-com-object-from-a-wcf-operation.aspx)但我的OperationContext.Current始终为null。任何建议都非常感谢。
服务
收集:
private static Dictionary<IAgent, COMAgent> agents = new Dictionary<IAgent, COMAgent>();
第一步:
public void Login(LoginRequest request)
{
IAgent agent = OperationContext.Current.GetCallbackChannel<IAgent>();
lock (agents)
{
if (agents.ContainsKey(agent))
throw new FaultException("You are already logged in.");
else
{
ICOMClass startup = new ICOMClass();
string server = ConfigurationManager.AppSettings["Server"];
int port = Convert.ToInt32(ConfigurationManager.AppSettings["Port"]);
bool success = startup.Logon(server, port, request.Username, request.Password);
if (!success)
throw new FaultException<COMFault>(new COMFault { ErrorText = "Could not log in." });
COMAgent comAgent = new COMAgent { Connection = startup };
comAgent.SomeEvent += new EventHandler<COMEventArgs>(comAgent_COMEvent);
agents.Add(agent, comAgent);
}
}
}
第二幕:
public void Logoff()
{
IAgent agent = OperationContext.Current.GetCallbackChannel<IAgent>();
lock (agents)
{
COMAgent comAgent = agents[agent];
try
{
bool success = comAgent.Connection.Logoff();
if (!success)
throw new FaultException<COMFault>(new COMFault { ErrorText = "Could not log off." });
agents.Remove(agent);
}
catch (Exception exc)
{
throw new FaultException(exc.Message);
}
}
}
答案 0 :(得分:0)
看看这篇非常相似的帖子:http://www.netfxharmonics.com/2009/07/Accessing-WPF-Generated-Images-Via-WCF
您必须使用OperationContextScope从新生成的线程访问当前的OperationContext:
System.Threading.Thread thread = new System.Threading.Thread(new System.Threading.ThreadStart(delegate
{
using (System.ServiceModel.OperationContextScope scope = new System.ServiceModel.OperationContextScope(context))
{
result = InnerOperationInvoker.Invoke(instance, inputs, out staOutputs);
}
}));