0

我正在尝试构建一个 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 始终为空。非常感谢任何建议。

服务

收藏:

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);
            }
        }
    }
4

1 回答 1

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);
        }
     }));
于 2010-10-12T09:01:16.890 回答