如何同时异步进行许多ping操作? [英] How can I make many pings asynchronously at the same time?

查看:109
本文介绍了如何同时异步进行许多ping操作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我似乎似乎不明白如何构造对SendPingAsync的异步调用.我想遍历一个IP地址列表,并异步遍历它们,然后再继续在程序中进行操作...现在一次要一次遍历所有IP地址永远是永远的.我早些时候问过一个问题,认为我可以弄清楚异步,但显然我错了.

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;
}

恐怕我只是不明白这里真正发生的事情……我什么时候应该返还任务?当我按原样运行时,我得到的是冻结的UI和ping错误.我已经在这里阅读了MSDN文档和大量问题,但我仍然没明白.

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.

推荐答案

您想要执行以下操作:

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

    return results.ToList();
}

这将异步启动theListOfIPs中每个IP的一个请求,然后异步等待它们全部完成.然后它将返回答复列表.

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.

请注意,与将结果设置在字段中相比,返回结果几乎总是更好.如果您在异步操作完成之前使用字段(pingReplies),则后者可能会导致错误-通过返回并在使用await进行调用之后将范围添加到集合中,可以使代码更清晰而且不易出错.

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.

这篇关于如何同时异步进行许多ping操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆