以下是一个示例代码,演示如何在关闭WCF服务主机时禁用通过按键关闭:
using System;
using System.ServiceModel;
namespace WcfServiceHostExample
{
class Program
{
static void Main(string[] args)
{
// 创建并启动WCF服务主机
using (ServiceHost host = new ServiceHost(typeof(MyService)))
{
host.Open();
Console.WriteLine("WCF服务已启动。按任意键关闭服务...");
// 等待按键关闭服务
Console.ReadKey();
// 禁用通过按键关闭
host.Close();
}
}
}
[ServiceContract]
public interface IMyService
{
[OperationContract]
string GetData();
}
public class MyService : IMyService
{
public string GetData()
{
return "Hello World";
}
}
}
在上面的示例中,我们使用了using
语句来创建和管理WCF服务主机的生命周期。在主机启动后,我们使用Console.ReadKey()
方法来等待用户按下任意键。当用户按下键后,我们直接调用host.Close()
方法来关闭服务主机,从而禁用了通过按键关闭服务的功能。
请注意,这只是一个示例代码,您需要根据自己的具体需求进行相应的修改和适配。