最近,在使用我的TCP/IP服务器和客户机时,我注意到它们在关闭它们后都保持在进程中打开。C#程序在关闭表单后继续在进程中运行
我通过将套接字配置到服务器上来解决了客户端处于打开状态,该套接字关闭了框架背景中的所有异步线程。
但是,当试图在服务器上这样做时,无论我做什么,该过程都保持打开状态。
假设TCP/IP服务器正在处理它自己的东西,这个代码中是否还有其他的东西可以保持这个过程的开放?
编辑:更新: 如果我在Program.cs中的Application.Run(new ServerForm())行后面放置一个断点,一旦按下exit或调用Application.Exit(),它就会中断。
我不知道它挂了什么程序,但它并没有退出Main。
namespace ChatServer
{
public partial class ServerForm : Form
{
private NetLib.Server _server = new NetLib.Server();
public delegate void ClientConnection(ServerNetworkState ns);
public ServerForm()
{
InitializeComponent();
}
private void ServerForm_Load(object sender, EventArgs e)
{
//Set up server IP and Port #.
_server.Ip = "127.0.0.1";
_server.Port = 5001;
//Setup events for success/error checking
_server.NewConnection += new NetLib.Server.NetworkStateEventHandler(_server_NewConnection);
_server.Started += new NetLib.Server.ServerEventHandler(_server_Started);
_server.Initialized += new NetLib.Server.ServerEventHandler(_server_Initialized);
_server.BindFailure += new NetLib.Server.ServerEventHandler(_server_BindFailure);
_server.BindSuccess += new NetLib.Server.ServerEventHandler(_server_BindSuccess);
//Initialize Server and add neccesary commands
_server.Initialize();
//Clients will call sendmessage on the server,
//and the server will send the message to the neccesary clients.
_server.MessageEncoder.FriendlyCommands.Add("sendmessage", SendMessage);
}
public void SendMessage(short sender, short[] recipients, string text)
{
_server.MessagePump.Enqueue(new Packet(-1, recipients, "receivemessage", text));
}
void _server_BindSuccess()
{
//Log Bind Success at DateTime.Now
}
void _server_BindFailure()
{
//Log Bind Failure at DateTime.Now
}
void _server_Initialized()
{
//Log Initialized at DateTime.Now
}
void _server_Started()
{
//Log Started at DateTime.Now
}
void _server_NewConnection(NetLib.ServerNetworkState ns)
{
//Log New Connection with ns.Ip at DateTime.Now
BeginInvoke(new ClientConnection(AddClientToControl), ns);
}
private void AddClientToControl(NetLib.ServerNetworkState ns)
{
listBox1.Items.Add("ID: " + ns.Id + " IP: " + ns.Ip);
}
private void startServer_Click(object sender, EventArgs e)
{
_server.Start();
}
private void ServerForm_FormClosing(object sender, FormClosingEventArgs e)
{
_server.Dispose();
}
}
}
我不知道NetLib.Server,但似乎你(或你的库)不设置线程的'IsBackground'属性为true。 – 2011-12-30 20:50:19
该库不使用System.Threading.Thread,而是使用Socket AsyncResults。 – 2011-12-30 20:58:11
也许你应该等待,看看它是否被处置> – 2011-12-30 21:01:05