使用SignalR。大量信息here 和here。 This article 看起来也很不错。
至于实际代码,创建一个WCF服务并使用NuGet添加对SignalR的引用,然后添加一个hub类:
public class ServiceMonitorHub : Hub
{
}
您还需要添加一个 Owin 启动类来启动 SignalR 集线器:
[assembly: OwinStartup(typeof(YourNamespace.SignalRStartup))]
namespace YourNamespace
{
public class SignalRStartup
{
public void Configuration(IAppBuilder app)
{
app.MapSignalR();
}
}
}
然后,您的服务处理程序可以获得对此集线器的引用并将消息发送到连接到它的所有客户端:
public class Service1 : IService1
{
public string GetData(int value)
{
// send msg to clients
var hub = GlobalHost.ConnectionManager.GetHubContext<ServiceMonitorHub>();
hub.Clients.All.BroadcastMessage();
return string.Format("You entered: {0}", value);
}
然后您的 WPF 客户端连接到此 SignalR 服务器并挂钩处理程序以接收服务处理程序发送的消息,此示例包含一个调用服务的按钮处理程序,以及与 SignalR 集线器的连接以接收消息反弹:
public partial class MainWindow : Window
{
private HubConnection Connection;
private IHubProxy HubProxy;
public MainWindow()
{
InitializeComponent();
Task.Run(ConnectAsync);
}
private void Button_Click(object sender, RoutedEventArgs e)
{
using (var service = new ServiceReference1.Service1Client())
service.GetData(1);
}
public async Task ConnectAsync()
{
try
{
this.Connection = new HubConnection("http://localhost:59082/");
this.HubProxy = this.Connection.CreateHubProxy("ServiceMonitorHub");
HubProxy.On("BroadcastMessage", () => MessageBox.Show("Received message!"));
await this.Connection.Start();
}
catch (Exception ex)
{
}
}
}
}
请注意,客户端需要 NuGet SignalR.Clients 包(而不仅仅是 SignalR)。
服务调用中心客户端还有其他方式,this link 显示了其他几种方式。