C#需要使用SendAsync返回最低Ping的帮助吗

C#需要使用SendAsync返回最低Ping的帮助吗,c#,asynchronous,console,ping,sendasync,C#,Asynchronous,Console,Ping,Sendasync,我有下面的代码,正在运行并ping所有Runescape游戏服务器,并在控制台中返回ip地址列表和相应的“往返”时间 编辑“忽略一些旧注释” 我遇到以下问题: A) 如何返回所有服务器中最低的ping并将其写入控制台 B) 如何跨方法返回当前“server.ToString()”的原始主机名或“number” public void buttonClick_Click(object sender, EventArgs e) { Console.WriteL

我有下面的代码,正在运行并ping所有Runescape游戏服务器,并在控制台中返回ip地址列表和相应的“往返”时间

编辑“忽略一些旧注释”

我遇到以下问题:

A) 如何返回所有服务器中最低的ping并将其写入控制台

B) 如何跨方法返回当前“server.ToString()”的原始主机名或“number”

    public void buttonClick_Click(object sender, EventArgs e)
    {
            Console.WriteLine();
            Ping();     
    }


    public static void Ping()
    {
        for (int server = 1; server <= 110; server++)
        {
            string hostname = "oldschool" + server.ToString() + ".runescape.com";

            // Get an object that will block the main thread.
            AutoResetEvent waiter = new AutoResetEvent(false);

            // Ping's the local machine.
            Ping pingSender = new Ping();

            // When the PingCompleted event is raised,
            // the PingCompletedCallback method is called.
            pingSender.PingCompleted += new PingCompletedEventHandler(PingCompletedCallback);

            // Create a buffer of 32 bytes of data to be transmitted.
            string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
            byte[] buffer = Encoding.ASCII.GetBytes(data);

            //Console.WriteLine("Send Before Async.");

            // Send the ping asynchronously.
            // Use the waiter as the user token.
            // When the callback completes, it can wake up this thread.
            pingSender.SendAsync(hostname, 1000, waiter);

            //Console.WriteLine("Ping example completed.");
        }
    }

    private static void PingCompletedCallback(object sender, PingCompletedEventArgs e)
    {
        // If the operation was canceled, display a message to the user.
        if (e.Cancelled)
        {
            Console.WriteLine("Ping canceled.");
            // Let the main thread resume. 
            // UserToken is the AutoResetEvent object that the main thread 
            // is waiting for.
            ((AutoResetEvent)e.UserState).Set();
        }
        // If an error occurred, display the exception to the user.
        if (e.Error != null)
        {
            Console.WriteLine("Ping failed:");
            Console.WriteLine(e.Error.ToString());
            // Let the main thread resume. 
            ((AutoResetEvent)e.UserState).Set();
        }
        PingReply reply = e.Reply;
        DisplayReply(reply);

        // Let the main thread resume.
        ((AutoResetEvent)e.UserState).Set();
    }

    public static void DisplayReply(PingReply reply)
    {
        List<long> lag = new List<long>();

        if (reply == null)
        return;

        Console.WriteLine("Status: {0}", reply.Status);

        if (reply.Status == IPStatus.Success)
        {
            Console.WriteLine("\r\n");
            Console.WriteLine("Address: {0}", reply.Address);
            Console.WriteLine("Ping: {0}", reply.RoundtripTime);
        }
        return;
    }
public void按钮单击(对象发送者,事件参数)
{
Console.WriteLine();
Ping();
}
公共静态无效Ping()
{

对于(intserver=1;server,我重新构造了代码,使其能够工作。我还使ping并行运行,这将加快结果的速度

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Net;
using System.Net.Sockets;
using System.Net.NetworkInformation;

namespace WindowsFormsApplication13
{
    public partial class Form1 : Form
    {
         public Form1()
        {
            InitializeComponent();


        }
    }
    public class State
    {
        public string ip { get; set;}
        public decimal roundTripTime { get; set; }
        public IPStatus status { get;set;}
    }
    public class myPing
    {
        static const int NUMBER_SERVERS = 110;
        public static List<State> states { get; set; }
        public static int count = 0;
        public myPing()
        {

            AutoResetEvent waiter = new AutoResetEvent(false);
            for (int server = 1; server <= NUMBER_SERVERS; server++)
            {
                string hostname = "oldschool" + server.ToString() + ".runescape.com";

                // Get an object that will block the main thread.

                // Ping's the local machine.
                Ping pingSender = new Ping();


                // When the PingCompleted event is raised,
                // the PingCompletedCallback method is called.
                pingSender.PingCompleted += new PingCompletedEventHandler(PingCompletedCallback);

                // Create a buffer of 32 bytes of data to be transmitted.
                string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
                byte[] buffer = Encoding.ASCII.GetBytes(data);

                //Console.WriteLine("Send Before Async.");

                // Send the ping asynchronously.
                // Use the waiter as the user token.
                // When the callback completes, it can wake up this thread.
                pingSender.SendAsync(hostname, 1000, waiter);

                //Console.WriteLine("Ping example completed.");
            }
            waiter.WaitOne();
            DisplayReply(states);

            Console.ReadLine();
        }

        private static void PingCompletedCallback(object sender, PingCompletedEventArgs e)
        {
            // If the operation was canceled, display a message to the user.
            if (e.Cancelled)
            {
                Console.WriteLine("Ping canceled.");
                // Let the main thread resume. 
                // UserToken is the AutoResetEvent object that the main thread 
                // is waiting for.
                ((AutoResetEvent)e.UserState).Set();
            }
            // If an error occurred, display the exception to the user.
            if (e.Error != null)
            {
                Console.WriteLine("Ping failed:");
                Console.WriteLine(e.Error.ToString());
                // Let the main thread resume. 
                ((AutoResetEvent)e.UserState).Set();
            }
            PingReply reply = e.Reply;

            State state = new State();

            Object thisLock = new Object();

            lock (thisLock)
            {
               states.Add(state);
            }
            state.ip = reply.Address.ToString();
            state.roundTripTime = reply.RoundtripTime;
            state.status = reply.Status;

            count++;
            // Let the main thread resume.
            if (count == NUMBER_SERVERS)
            {
                ((AutoResetEvent)e.UserState).Set();
            }
        }

        public static void DisplayReply(List<State> replies)
        {
            foreach (State reply in replies)
            {
                Console.WriteLine("Status: {0}", reply.status);

                if (reply.status == IPStatus.Success)
                {
                    Console.WriteLine("\r\n");
                    Console.WriteLine("Address: {0}", reply.ip);
                    Console.WriteLine("Ping: {0}", reply.roundTripTime);
                }
            }
            State shortest = replies.OrderBy(x => x.roundTripTime).FirstOrDefault();
            Console.WriteLine("Shortest Route IP : '{0}'  Time : '{1}'", shortest.ip.ToString(), shortest.roundTripTime.ToString() );
        }
    }


}
使用系统;
使用System.Collections.Generic;
使用系统组件模型;
使用系统数据;
使用系统图;
使用System.Linq;
使用系统文本;
使用System.Windows.Forms;
使用系统线程;
Net系统;
使用System.Net.Sockets;
使用System.Net.NetworkInformation;
命名空间Windows窗体应用程序13
{
公共部分类Form1:Form
{
公共表格1()
{
初始化组件();
}
}
公共阶级国家
{
公共字符串ip{get;set;}
公共十进制roundTripTime{get;set;}
公共IPStatus状态{get;set;}
}
公共类myPing
{
静态常量int NUMBER_服务器=110;
公共静态列表状态{get;set;}
公共静态整数计数=0;
公共myPing()
{
自动重置事件服务员=新自动重置事件(假);

对于(int server=1;server你需要所有回拨的东西吗?使用PLinq和同步发送方法,你可以有大约5行代码来完成所有这些。我想我在使用异步时遇到了一个问题&返回所有的回复细节,对C#来说很新,所以这对我来说有点混乱!嗨,谢谢你的回复,很抱歉te回复,我很感激。我已经试过运行您为我重新编写的代码。我似乎根本没有在控制台上写入任何内容,不知道哪里出了问题!在下面的帖子中查看我的答案。我知道的代码是有效的。如果您将下面的代码添加到以前的帖子中,您将获得最低的往返时间:I a在上一篇文章的代码中添加了几行以获得最短时间:MyPing ping=new MyPing(dt);List replies=dt.AsEnumerable()。其中(x=>x.Field(“Reply”)!=null)。选择(x=>x.Field(“Reply”)。选择多(x=>x)。ToList();long ShortTime=replies.Min(x=>x.RoundtripTime);