C#Ping速度不够快

时间:2018-04-11 20:19:30

标签: c# asynchronous timeout ping

我正在尝试扫描电脑是在线还是离线。 但我现在的代码是慢速扫描的方式,具有良好的性能,就像计算机处于脱机状态一样,延迟时间为3到5秒。 我甚至将超时参数设置为500,但如果计算机处于脱机状态,则仍需要超过3秒。

public bool PingComputer(string computername)
    {
        bool check = false;
        Ping ping = new Ping();
        try
        {
            PingReply reply = ping.Send(computername, 500);
            check = reply.Status == IPStatus.Success;
        }
        catch (PingException)
        {

        }
        return check;
    }

我也已经读过有关异步ping但我找不到合适的解决方案,如果计算机在线则返回true,如果离线则返回false。

提前致谢。

1 个答案:

答案 0 :(得分:0)

如果您假装对计算机列表执行Ping操作,则可以使用Parallel或使用异步Task

我用相同的77个IP测试了这两种方法。使用了变量sec = 3

  • 任务执行时间为00:00:02.7146249
  • 平行托克00:00:05.9941404

使用方法

Dictionary<string, bool> pingsReturn = await Network.PingListAsync(dictionary,3);

我可以举两个例子:

任务

public static async Task<Dictionary<string, bool>> PingListAsync(Dictionary<string, bool> HostList, int sec = 3)
        {

            // Create a buffer of 32 bytes of data to be transmitted.
            string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
            byte[] buffer = Encoding.ASCII.GetBytes(data);
            // set a quick TTL
            PingOptions options = new PingOptions(20, true);

            // internal support Task to handle Ping Exceptions like "host not found"
            async Task<KeyValuePair<string, bool>> PingHost(string host)
            {
                try
                {
                    var pingresult = await Task.Run(() => new Ping().SendPingAsync(host, sec * 1000, buffer, options));
                    //t.Wait();
                    if (pingresult.Status == IPStatus.Success)
                        return new KeyValuePair<string, bool>(host, true);
                    else
                        return new KeyValuePair<string, bool>(host, false);

                }
                catch
                {
                    return new KeyValuePair<string, bool>(host, false);
                }

            }

            //Using Tasks >>
            var watch = new Stopwatch();
            watch.Start();
            var tasksb = HostList.Select(HostName => PingHost(HostName.Key.ToString()));

            var pinglist = await Task.WhenAll(tasksb);


            foreach (var pingreply in pinglist)
            {
                HostList[pingreply.Key] = pingreply.Value;
            }

            watch.Stop();
            Log.Debug("PingList (Tasks) Time elapsed: " + watch.Elapsed);
            //Using Tasks <<



            return HostList;

        }

平行

public static async Task<Dictionary<string, bool>> PingListAsync(Dictionary<string, bool> HostList, int sec = 3)
        {

            // Create a buffer of 32 bytes of data to be transmitted.
            string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
            byte[] buffer = Encoding.ASCII.GetBytes(data);
            // set a quick TTL
            PingOptions options = new PingOptions(20, true);

            //Using Parallel >>
            watch = new Stopwatch();
            watch.Start();

            // avoid exception "Collection was modified; enumeration operation may not execute."
            // we need new dictionary and add values
            Dictionary<string, bool> dictionary = new Dictionary<string, bool>();
            Parallel.ForEach(HostList.Keys, (currHost) =>
            {

                try
                {
                    var pingReply = new Ping().Send(currHost, sec * 1000, buffer, options);
                    if (pingReply.Status == IPStatus.Success)
                        dictionary.Add(currHost, true);
                    else
                        dictionary.Add(currHost, false);
                }
                catch
                {
                    // handle Ping Exceptions like "host not found"
                    dictionary.Add(currHost, false);
                }


            });
            watch.Stop();
            Log.Debug("PingList (Parallel) Time elapsed: " + watch.Elapsed);
            //Using Parallel <<

            return dictionary;

        }

PS-我知道这是一个老问题,但仍然有效。