首页 新闻 会员 周边 捐助

wpf 怎样让BackgroundWorker强行结束,或者设置TcpListener的超时时间??

0
悬赏园豆:5 [已解决问题] 解决于 2012-07-25 13:16

我利用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的超时时间,一段时间监听不到 就引发异常?????

wpf
xiaxia—博客园的主页 xiaxia—博客园 | 初学一级 | 园豆:128
提问于:2012-01-07 21:28
< >
分享
最佳答案
1

可以尝试使用AcceptTcpClient的异步版本BeginAcceptTcpClient

参考msdn

http://msdn.microsoft.com/zh-cn/library/system.net.sockets.tcplistener.beginaccepttcpclient(v=VS.80).aspx

收获园豆:5
klice | 初学一级 |园豆:173 | 2012-01-08 16:38
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册