我有多线程 TcpListener。从按钮开始
private void startServer_Click(object sender, EventArgs e)
{
Server = new Thread(ServerThread);
Server.Start();
}
ServerThread 的方法如下所示:
protected void ServerThread()
{
try
{
....;
serverListener = new TcpListener(localAddr, port);
serverListener.Start();
while (true)
{
Application.DoEvents();
while (!serverListener.Pending()) Thread.Sleep(500);
ConnectionThread newconnection = new ConnectionThread(mainClient);
}
}
catch (SocketException error)
{
.....;
}
finally
{
serverListener.Stop();
}
}
这里 ConnectionThread 类看起来像:
class ConnectionThread
{
public ConnectionThread(Action<object> methodWork)
{
ThreadPool.QueueUserWorkItem(new WaitCallback(methodWork));
}
}
在这里,我的方法看起来像:
public void mainClient(object state)
{
TcpClient client = serverListener.AcceptTcpClient();
NetworkStream stream = client.GetStream();
Byte[] bytes = new Byte[25600000];
String data = null;
int i;
while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
{
....
}
stream.Close();
client.Close();
}
毕竟我有停止服务器按钮,看起来像:
private void stopServer_Click(object sender, EventArgs e)
{
Server.Abort();
serverListener.Server.Close();
serverListener.Stop();
}
一切正常。在使用 tcplistener 并尝试停止它之后 - 它会在 1 秒内停止并得到错误 WSACancelBlockingError。我知道这个错误是因为我试图从另一个线程停止 TcpListener。但是我该如何解决呢?制定行动<>?这是个好决定吗?