Ping 异步问题

Ping ASync Problems

我必须在下面指示的行上有一个断点才能使以下代码正常工作。否则,程序将无限期暂停。

    async Task<List<PingReply>> PingAsync()
    {
        var pingTargetHosts = GetIPs();
        var pingTasks = pingTargetHosts.Select(host => new Ping().SendPingAsync(host, 2000)).ToList();
        var pingResults = await Task.WhenAll(pingTasks); //THIS LINE NEEDS A BREAKPOINT TO WORK
        return pingResults.ToList();
    }

代码是这样调用的

        List<PingReply> GetReplies()
    {
        var PingIPs = PingAsync();
        MessageBox.Show("Loading:...");
        List<PingReply> Results = PingIPs.Result;
        return Results;
    }

任何人都可以告诉我如何修改我的代码以删除断点但仍然有一段功能代码。

编辑: 未经测试,但 99% 确定这会起作用。

async Task<List<PingReply>> PingAsync()
    {
        var pingTargetHosts = GetIPs();
        var pingTasks = pingTargetHosts.Select(async host => await new Ping().SendPingAsync(host, 2000)).ToList();
        var pingResults = await Task.WhenAll(pingTasks);
        return pingResults.ToList();
    }

    async Task<List<PingReply>> GetReplies()
    {
        var PingIPs = PingAsync();
        MessageBox.Show("Loading:...");
        return await PingIPs;
    }

    async Task BuildDictionary()
    {
        List<PingReply> Replies = await GetReplies();
        //Use this list via foreach
    }
    async private void button1_Click(object sender, EventArgs e)
    {
        EthernetCheck checker = new EthernetCheck();
        checker.Check();
        bool IsEthernetIn = checker.PluggedIn;
        if (IsEthernetIn)
        {
            await BuildDictionary();
            //Do Stuff
        }           
    }

使用时async/await你要记住.net framework会控制程序执行的流程,所以我建议你把所有的调用都设为异步来避免这种问题。

async Task<List<PingReply>> PingAsync()
{
    var pingTargetHosts = await GetIPs();
    var pingTasks = pingTargetHosts.Select(host => await new Ping().SendPingAsync(host, 2000)).ToList();
    var pingResults = await Task.WhenAll(pingTasks);
    return pingResults.ToList();
}

您的代码陷入僵局,因为您 blocking on asynchronous code. To fix it, use async all the way:

async Task<List<PingReply>> GetRepliesAsync()
{
  var PingIPs = PingAsync();
  MessageBox.Show("Loading:...");
  return await PingIPs;
}

用法:

var replies = await GetRepliesAsync();