C#Ping.Send()无限期,这会大大降低计算机的速度

简而言之,我有两个主要问题:

1-有没有可能无限期地使用该类中的Send()方法Ping

2-这会导致计算机速度大大降低吗?

我正在编写一个程序,可以在短时间内建立到特定服务器的平均ping,并在ping(ms)超过平均值的某个点以上时通知用户。现在,要完成此操作,我自然要使程序永远对服务器进行ping操作(当然,直到程序关闭为止)。

如果没有办法可以永远做到这一点,那么我只能想到存在一个不合理的大for循环或一个while (true) {}循环。

我只是担心这会给用户的计算机造成很大的压力。可以确认吗?还是我太谨慎了?


扬帆大鱼
浏览 638回答 1
1回答

冉冉说

如果您想变得超级高效,请使用Async IO-这样,您的应用程序就可以重用现有线程,而无需处理阻塞调用(从而不必要地消耗了线程):public async Task PingForeverAsync( IPAddress host ){&nbsp; &nbsp; Ping ping = new Ping();&nbsp; &nbsp; while( true )&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; Task interval = Task.Delay( 5000 );&nbsp; &nbsp; &nbsp; &nbsp; Task<PingReply> pingTask = ping.SendAsync( host, 5000 );&nbsp; &nbsp; &nbsp; &nbsp; PingReply reply = await pingTask.ConfigureAwait(false);&nbsp; &nbsp; &nbsp; &nbsp; // (Measure the reply time here and send out notification if necessary)&nbsp; &nbsp; &nbsp; &nbsp; await interval.ConfigureAwait(false); // await the 5000ms interval delay&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP