我利用BackgroundWorker新建一个线程来接受TCP上传来的数据,但是想要停止接受的时候遇到问题了.dowork事件函数如下:
void recieveWorker_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker work = sender as BackgroundWorker;
int port = (int)e.Argument;
TcpListener tcpListener;
TcpClient tcpClient;
NetworkStream networkStream;
tcpListener = new TcpListener(IPAddress.Any, port);
IPEndPoint clientPoint;
string receiveStr = "";
byte[] reveiveByte = new byte[1024];
int bytes = 0;
try
{
tcpListener.Start();
}
catch(Exception exp)
{
MessageBox.Show(exp.Message);
return;
}
while(!work.CancellationPending)
{
try
{
tcpClient = tcpListener.AcceptTcpClient();
}
catch (Exception exp)
{
MessageBox.Show(exp.Message);
return;
}
clientPoint = (IPEndPoint)(tcpClient.Client.RemoteEndPoint);
networkStream = tcpClient.GetStream();
try
{
receiveStr = "";
while (true)
{
bytes = networkStream.Read(reveiveByte, 0, reveiveByte.Length);
if (bytes <= 0)
break;
receiveStr += Encoding.ASCII.GetString(reveiveByte, 0, bytes);
}
networkStream.Close();
work.ReportProgress(0, receiveStr);
}
catch(Exception exp)
{
MessageBox.Show(exp.Message);
}
tcpClient.Close();
tcpListener.Stop();
}
}
我调用recieveWorker.CancelAsync();企图结束线程,但是线程会阻塞在
tcpClient = tcpListener.AcceptTcpClient();直到有数据过来.进入下一个
while(!work.CancellationPending)循环的时候线程才会退出.
请问各位高手,有没有什么方法可以强行结束backgroundworker,或者设置一下TcpListener的超时时间,一段时间监听不到 就引发异常?????
可以尝试使用AcceptTcpClient的异步版本BeginAcceptTcpClient
参考msdn