使用控制台程序寄宿wcf服务时,为了程序不退出,会使用Console.Read()方法来等待用户输入以确保程序不会退出。
刚开始代码是这样实现的。
using (ServiceHost host = new ServiceHost(typeof(CalculatorService)))
{
host.Opened += delegate
{
Console.WriteLine("CalculaorService已经启动,按任意键终止服务!");
};
host.Open();
}
Console.Read();
下面是客户端的调用代码。
using (ChannelFactory<ICalculator> channelFactory = new ChannelFactory<ICalculator>("calculatorservice"))
{
ICalculator proxy = channelFactory.CreateChannel();
Console.WriteLine("x + y = {2} when x = {0} and y = {1}", 1, 2, proxy.Add(1, 2));
}
执行到proxy.Add(1, 2)时,会出现下面的错误提示。
可见服务寄宿并没有成功。
修改代码,如下所示,就能正常调用服务了。
using (ServiceHost host = new ServiceHost(typeof(CalculatorService)))
{
host.Opened += delegate
{
Console.WriteLine("CalculaorService已经启动,按任意键终止服务!");
};
host.Open();
Console.Read();
}
仅仅是将Console.Read()代码移至using代码块内,为什么会这样呢。会知道的吱呀一声。