c# - Windows 监听器服务

标签 c# multithreading windows-services tcplistener

我如何用 C# 编写 Windows 服务来监听 tcp 连接并处理这些连接?问题是我想要一个比在主线程中“阻塞”更好的方法,例如

while(true) ;

我可以在另一个线程上启动监听器,但主线程需要阻塞以防止应用程序退出(以及服务停止)。 谢谢。

最佳答案

为什么不使用 WCF 服务? - 您可以在 Windows 服务中托管 WCF 服务....然后您可以使用 NetTcpBinding(以便通过 tcp 进行通信) 所以我们的代码看起来像

namespace WindowsService1
{
    public partial class Service1 : ServiceBase
    {
        internal static ServiceHost myServiceHost = null;

        public Service1()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            if (myServiceHost != null)
            {
                myServiceHost.Close();
            }
            myServiceHost = new ServiceHost(typeof(WcfServiceLibrary1.Service1));
            myServiceHost.Open();
        }

        protected override void OnStop()
        {
            if (myServiceHost != null)
            {
                myServiceHost.Close();
                myServiceHost = null;
            }
        }
    }
}

以下是一些示例: http://www.pluralsight.com/community/blogs/aaron/archive/2008/12/02/screencast-hosting-wcf-services-in-windows-services.aspx http://msdn.microsoft.com/en-us/library/ms733069.aspx

关于c# - Windows 监听器服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/906661/

相关文章:

C# 类与结构

c# - 你如何使用 MVC/Razor 封装 logic/html

ios - 如何创建和管理串行后台线程

c# - 程序关闭后远程服务关闭

c# - 在 Windows 服务中模拟用户

javascript - WebView.InvokeScriptAsync 不适用于通用应用程序

c# - Object[] 到 double[] c#

c# - 如果我只想以线程安全的方式测试和设置标志,那么线程类是什么?

python - Python中多处理或多线程的动态刷新打印

powershell - 使用 PowerShell 获取 Windows Server 上所有已停止自动服务的属性