2009-10-08 141 views
10

我需要做一些关于WCF服务功能的实时报告。该服务是在Windows应用程序中自行托管的,并且我的要求是在客户端调用某些方法时向主机应用程序报告“实时”。订阅WCF服务中的事件

我最初的想法是在服务代码中发布“NotifyNow”事件,并在我的调用应用程序中订阅事件,但这似乎不可能。在我的服务代码(实现,而不是接口),我曾尝试加入以下

public delegate void MessageEventHandler(string message); 
public event MessageEventHandler outputMessage; 

void SendMessage(string message) 
{ 
    if (null != outputMessage) 
    { 
     outputMessage(message); 
    } 
} 

,并调用SendMessage函数方法,每当我需要通知一些动作的主机应用程序。 (这是基于我在WinForms应用程序中记录的这种形式间通信,而我的记忆可能让我失望......)

当我尝试在我的主机中挂接事件处理程序时不过,我似乎无法弄清楚如何连接到事件......我的托管代码是(简而言之)

service = new ServiceHost(typeof(MyService)); 
service.outputMessage += new MyService.MessageEventHandler(frm2_outputMessage); 
    // the above line does not work! 
service.Open(); 

(包裹在一个try/catch)。

任何人都可以帮忙,告诉我如何让这种方法起作用,或者指点我一个更好的方法。

TIA

回答

11

我今天早上做了一些更多的研究,发现了一个比已经概述的更简单的解决方案。信息的主要来源是this page,但总结在这里。

1)在服务类,添加以下(或类似)代码..

public static event EventHandler<CustomEventArgs> CustomEvent; 

public void SendData(int value) 
{  
    if (CustomEvent != null) 
     CustomEvent(null, new CustomEventArgs()); 
} 

最重要的一点是使事件静态的,否则你就没有抓住它的机会。

2)定义CustomEventArgs类,例如...

public class CustomEventArgs : EventArgs 
{ 
    public string Message; 
    public string CallingMethod;       
} 

3)添加调用中,你有兴趣在服务的每个方法的代码...

public string MyServiceMethod() 
{ 
    SendData(6); 
} 

4)将ServiceHost实例化为正常,并挂入事件中。

ServiceHost host = new ServiceHost(typeof(Service1)); 
Service1.CustomEvent += new EventHandler<CustomEventArgs>(Service1_CustomEvent); 
host.Open(); 

5)手柄的事件消息冒泡从那里主机。

+0

CustomEvent不会显示在Service1下。这是否适用于WCF 4.5? – 2013-05-09 19:22:29

1

你似乎实例化一个默认ServiceHost类:

service = new ServiceHost(typeof(MyService)); 
       *********** 
service.outputMessage += new MyService.MessageEventHandler(frm2_outputMessage); 
    // the above line does not work! 

我强烈怀疑这将有一个事件处理程序“outputMessage”属性。

你不应该被实例化自己的自定义服务主机,这样的事情:

class MyCustomServiceHost : ServiceHost 
{ 
    ...... your custom stuff here ...... 
} 

service = new MyCustomServiceHost(typeof(MyService)); 
       ******************* 
service.outputMessage += new MyService.MessageEventHandler(frm2_outputMessage); 

Marc

+0

这看起来像一个很好的解决方案,但我不得不承认我不知道我会如何去做......我一直和你在一起......直到你在这里定制的东西...... :(我怀疑我将要面对的问题仍然围绕在服务 – ZombieSheep 2009-10-08 12:19:11

+0

中的主要事件处理代码中。回到家后,我的思绪停止了一段时间,我清楚地知道你在说什么 - 我在看ServiceHost,而不是服务的实例......我需要再看看它,明白我需要在自定义ServiceHost中编码来传递事件通过。谢谢 – ZombieSheep 2009-10-08 19:43:28

11

服务变量是ServiceHost的一个实例,而不是您的服务实现。尝试像这样:

MyService myService = new MyService(); 
myService.outputMessage += new MyService.MessageEventHandler(frm2_outputMessage); 
host = new ServiceHost(myService); 
+0

Upvoted,虽然我没有沿着这条路线走下去 - 我今天下午遇到了一些问题,这意味着我无法在其上花费所需的时间。:) – ZombieSheep 2009-10-08 19:44:12

+0

像魅力一样工作 – Eric 2012-07-11 14:25:34