yub*_*ben 3 c# multithreading windows-services tcplistener
如何在c#中编写一个监听tcp连接并处理这些连接的Windows服务?问题是我想要一个比在主线程中"阻塞"更好的方法,例如
while(true) ;
我可以在另一个线程上启动监听器,但主线程需要阻止以防止应用程序退出(并且服务停止).谢谢.
为什么不使用WCF服务? - 你可以在一个窗口服务主机WCF服务....然后你就可以(以通过TCP通讯)使用NetTcpBinding的所以我们的代码看起来像
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;
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
下面是一些样本: 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