C# 阻止程序关闭
我正在编写一个名为pipeserver的WCF。我有这样的想法:C# 阻止程序关闭,c#,wcf,C#,Wcf,我正在编写一个名为pipeserver的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
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之后添加whiletrue循环?因为这个解决方案在我看来很蹩脚。通常,您会这样做:-
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
}
}
}
退出事件为您提供了一种干净地终止进程的方法,使用事件可以让操作系统减少程序在等待数据到达时消耗的CPU时间。这是您可以做的最基本的事情!是:
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 取决于您的体系结构。您是否作为控制台应用程序托管此应用程序?windows应用程序winform/WPF、windows服务、IIS?该应用程序是执行其他活动还是仅运行服务并执行行为?我的意思是,我想一定是非阻塞呼叫。因此,如果执行while true,线程将阻塞..此外,.Net版本是什么?