我按照这个例子在两个C#项目之间创建了一个WCF接口:
https://dopeydev.com/wcf-interprocess-communication/
正如您在" TestService.cs"中看到的那样。代码,有这个函数的实现:
public void SendMessage(string message)
{
MessageBox.Show(message);
}
实际上显示了服务器上收到的消息。我知道这个名字很混乱,但它与客户使用的名称相同。
我的目标是更改此功能,以便触发要在另一个类中使用的事件。
这就是我试图做的事情:
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)]
public class IServer : Interfaces.IService
{
public void Connect()
{
Callback = OperationContext.Current.GetCallbackChannel<Interfaces.ICallbackService>();
}
public static Interfaces.ICallbackService Callback { get; set; }
public void SendMessage(string message)
{
MessageReceivedEventArgs args = new MessageReceivedEventArgs();
args.json = message;
OnMessageReceived(this, args);
}
public event EventHandler<MessageReceivedEventArgs> MessageReceived;
protected virtual void OnMessageReceived(object sender, MessageReceivedEventArgs e)
{
MessageReceived?.Invoke(this, e);
}
}
public class MessageReceivedEventArgs : EventArgs
{
public string json;
}
然后在我的另一堂课:
class Comm
{
IServer m_server = new IServer();
public Engine()
{
var host = new ServiceHost(typeof(IServer), new Uri("net.pipe://localhost"));
host.AddServiceEndpoint(typeof(IService), new NetNamedPipeBinding(), "ipc");
host.Open();
m_server.MessageReceived += Server_MessageReceived;
}
private void Server_MessageReceived(object sender, MessageReceivedEventArgs e)
{
// this event handler is never executed!
}
}
据我了解,问题是我在添加了事件处理程序的情况下创建了IServer
类的新实例,但实际使用ServiceHost
代码的IServer
是另一个实例
我错了吗?
我需要检索ServiceHost
使用的实例以使事件有效吗?
答案 0 :(得分:1)
ServiceHost
有an overload where you can provide your own instance for the service:
var host = new ServiceHost(m_server, new Uri("net.pipe://localhost"));
此外,您应该绑定事件之前启动服务,否则您可能会错过请求:
m_server.MessageReceived += Server_MessageReceived;
host.Open();