본문 바로가기
카테고리 없음

WPF & C# - ping 핑 비동기 테스트 ( await task.WhenAll )

by insurang 2020. 2. 2.
728x90
반응형
 WPF & C# - ping 핑 비동기 테스트 ( await task.WhenAll  )

pingTest.zip
0.08MB
pingTest.exe
0.01MB

 

 

MainWindow.xaml

<StackPanel>
    <TextBox x:Name="tbx"></TextBox>
    <Button x:Name="btn" Content="a" Click="Btn_Click"></Button>
    <Label x:Name="lbl" ></Label>
</StackPanel>

 

MainWindow.xaml.cs

    private void Btn_Click(object sender, RoutedEventArgs e)
    {
        lbl.Content = "";
        Ping_Send();
    }

    private async void Ping_Send()
    {
        var tokenSource = new CancellationTokenSource();

        string gate_ip = tbx.Text;
        string[] array = gate_ip.Split('.');

        List<Task> tasks = new List<Task>();
        for (int i = 1; i <= 254; i++)
        {
            string ping_var = array[0] + "." + array[1] + "." + array[2] + "." + i;

            var task = Task.Factory.StartNew(() =>
            {
                if (tokenSource.Token.IsCancellationRequested) return;

                //time in milliseconds           
                Ping(ping_var, 1, 14000, tokenSource.Token);
            }, tokenSource.Token);
            tasks.Add(task);
        }

        await Task.WhenAll(tasks.ToArray());
    }

    public void Ping(string host, int attempts, int timeout, CancellationToken cancellationToken)
    {
        try
        {
            Ping ping = new Ping();
            cancellationToken.Register(() => ping.SendAsyncCancel());
            ping.PingCompleted += new PingCompletedEventHandler(PingCompletedCallback);
            ping.SendAsync(host, timeout,host);
        }
        catch { }
    }

    private void PingCompletedCallback(object sender, PingCompletedEventArgs e)
    {
        this.lbl.Dispatcher.Invoke((ThreadStart)(() => {
            lbl.Content += e.UserState + "  / " +
            e.Reply.RoundtripTime + "\n";
        }), DispatcherPriority.ApplicationIdle);
    }

2021-02-19 변경내용

for (int i = 1; i <= 255; i++) 이부분의 255가

for (int i = 1; i <= 254; i++) 이렇게 254가 되어야 한다. 왜그랬을까...

728x90
반응형