我正在编写一个名为管道服务器的WCF。我有这样的事情:
class Program
{
static void Main(string[] args)
{
using(var host = new ServiceHost(typeof(XServer), new Uri("net.pipe://localhost")))
{
host.AddServiceEndpoint(typeof(IXServer), new NetNamedPipeBinding(), "XServer");
host.Open();
}
}
}
点击host.Open();
后程序停止工作。这个程序应该是一个服务器,所以它必须一直运行。我该怎么做?我需要在while(true)
之后添加host.Open()
循环吗?因为那个解决方案看起来很蹩脚。
答案 0 :(得分:2)
一般来说,你会做这样的事情: -
class Program
{
static void Main(string[] args)
{
using(var host = new ServiceHost(typeof(XServer), new Uri("net.pipe://localhost")))
{
host.AddServiceEndpoint(typeof(IXServer), new NetNamedPipeBinding(), "XServer");
host.Open();
create an exit event
while (true)
{
begin asynchronous read
wait on asynchronous read or exit event <- puts thread to sleep
if event was exit event, break out of while loop
parse read data
}
destroy exit event
}
}
}
exit事件为您提供了一种干净地终止进程的方法,并且使用事件可以减少程序在等待数据到达时消耗的CPU时间。
答案 1 :(得分:1)
你可以做的最基本的事情(阻止!)是:
class Program
{
private static ManualResetEventSlim _manualResetEventSlim;
static void Main(string[] args)
{
using(var host = new ServiceHost(typeof(XServer), new Uri("net.pipe://localhost")))
{
host.AddServiceEndpoint(typeof(IXServer), new NetNamedPipeBinding(), "XServer");
host.Open();
_manualResetEventSlim.Wait(); //This will **block** the application thread, But its not supposed to block your WCF Service host thread.
}
}
}
不要忘记在Dispose()上设置事件。