Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
285 views
in Technique[技术] by (71.8m points)

c# - How can I make many pings asynchronously at the same time?

I just can't seem to understand how to structure an asynchronous call to SendPingAsync. I want to loop through a list of IP addresses and ping them all asynchronously before moving on in the program... right now it takes forever to go through all of them one at a time. I asked a question about it earlier thinking I'd be able to figure out async but apparently I was wrong.

private void button1_Click(object sender, EventArgs e)
{
    this.PingLoop();
    MessageBox.Show("hi"); //for testing

}

public async void PingLoop()
{
    Task<int> longRunningTask = PingAsync();

    int result = await longRunningTask;
    MessageBox.Show("async call is finished!"); 

    //eventually want to loop here but for now just want to understand how this works
}

private async Task<int> PingAsync()
{
    Ping pingSender = new Ping();
    string reply = pingSender.SendPingAsync("www.google.com", 2000).ToString();
    pingReplies.Add(reply); //what should i be awaiting here?? 
    return 1;
}

I'm afraid I just don't get what is really going on here enough... when should I return a task? When I run this as is I just get a frozen UI and a ping error. I have read the MSDN documentation and tons of questions here and I'm just not getting it.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You'd want to do something like:

private async Task<List<PingReply>> PingAsync()
{
    var tasks = theListOfIPs.Select(ip => new Ping().SendPingAsync(ip, 2000));
    var results = await Task.WhenAll(tasks);

    return results.ToList();
}

This will start off one request per IP in theListOfIPs asynchronously, then asynchronously wait for them all to complete. It will then return the list of replies.

Note that it's almost always better to return the results vs. setting them in a field, as well. The latter can lead to bugs if you go to use the field (pingReplies) before the asynchronous operation completes - by returning, and adding the range to your collection after the call is made with await, you make the code more clear and less bug prone.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...