首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C# Ping不够快

C# Ping不够快
EN

Stack Overflow用户
提问于 2018-04-11 20:19:29
回答 1查看 1.2K关注 0票数 1

我试图做一个扫描,无论pc是在线还是离线。但是我现在的代码是缓慢扫描的方式,它的性能很好,就像一台计算机离线一样,有3到5秒的延迟。我甚至添加了设置为500的超时值参数,但是如果一台计算机离线仍然需要超过3秒。

代码语言:javascript
复制
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;
    }

我也读过有关异步pings的文章,但是我无法找到一个合适的解决方案,如果计算机是在线的,则返回true,如果它是脱机的,返回false。

提前谢谢。

EN

回答 1

Stack Overflow用户

发布于 2019-12-13 16:46:16

如果您假装要打开一个计算机列表,您可以使用Parallel或异步Task

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

  • 任务: 00:00:02.7146249
  • 平行线: 00:00:05.9941404

使用这些方法

代码语言:javascript
复制
Dictionary<string, bool> pingsReturn = await Network.PingListAsync(dictionary,3);

我可以给你两个例子:

任务

代码语言:javascript
复制
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;

        }

并行

代码语言:javascript
复制
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;

        }

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49783860

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档