【发布时间】:2015-02-25 21:10:44
【问题描述】:
我想在 ip + 端口上进行异步连续 ping 请求。 问题是,当目标服务器离线时,整个程序在请求期间冻结。但这不应该发生。
这是我的 ping 函数,在启动程序时会调用一次。 它应该每 3 秒执行一次 ping 请求。
public async void Start(string ip)
{
Stopwatch watch = new Stopwatch();
while (true)
{
watch.Restart();
using (TcpClient tcp = new TcpClient())
{
//try to connect to a closed port
IAsyncResult res = tcp.ConnectAsync("127.0.0.1", 1234);
//during the following while-loop the whole program freezes
//although this is an asynchronous function
while (watch.ElapsedMilliseconds < 1000)
{
if (tcp.Connected)
{
break;
}
}
watch.Stop();
if (tcp.Connected)
{
StatusControl.Text = watch.ElapsedMilliseconds.ToString() + " ms";
}
else
{
StatusControl.Text = "Offline";
}
}
//wait 3secs for the next request
await Task.Delay(3000);
}
}
【问题讨论】:
-
如果你想ping一台机器,使用ping,而不是
tcpClient.Connect -
遗憾的是,Ping 不支持端口,不是吗?
-
perlmonks.org/?node=xy+problem 解释一下你真正的问题怎么样。
标签: c# .net asynchronous tcpclient freeze