I'm making a C# Pinger in WPF using Ping() and BackgroundWorker(). Here is my full code:
using System;
using System.ComponentModel;
using System.Net.NetworkInformation;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows;
using System.Windows.Media;
namespace Pinger
{
public partial class MainWindow : Window
{
[DllImport("wininet.dll")] private static extern bool InternetGetConnectedState(out int Description, int ReservedValue);
public static bool IsConnectedToInternet() { return InternetGetConnectedState(out _, 0); }
private readonly BackgroundWorker BackWork_Pinger = new BackgroundWorker();
private int counter = 0; private readonly Ping pinger = new Ping();
public MainWindow()
{
InitializeComponent();
BackWork_Pinger.WorkerReportsProgress = true;
BackWork_Pinger.DoWork += (_, args) => { for (int i = 1; i > 0; ++i) { if (IsConnectedToInternet()) { BackWork_Pinger.ReportProgress(i); Thread.Sleep(100); } } };
BackWork_Pinger.ProgressChanged += (_, args) =>
{
try
{
PingReply pingReply = pinger.Send("8.8.8.8");
if (pingReply != null)
{
switch (pingReply.Status)
{
case IPStatus.Success:
int PingNumber = Convert.ToInt32(pingReply.RoundtripTime);
if (PingNumber < 100) { Ping_Value.Foreground = Brushes.Lime; Ping_Value.Text = PingNumber + " ms"; }
else if (PingNumber < 300) { Ping_Value.Foreground = Brushes.Yellow; Ping_Value.Text = PingNumber + " ms"; }
else if (PingNumber < 500) { Ping_Value.Foreground = Brushes.DarkOrange; Ping_Value.Text = PingNumber + " ms"; }
else { Ping_Value.Foreground = Brushes.Red; Ping_Value.Text = "Bad"; }
break;
case IPStatus.TimedOut: Ping_Value.Foreground = Brushes.WhiteSmoke; Ping_Value.Text = "Disconnected"; break;
default: Ping_Value.Foreground = Brushes.WhiteSmoke; Ping_Value.Text = "Disconnected"; break;
}
}
else { Ping_Value.Foreground = Brushes.WhiteSmoke; Ping_Value.Text = "Disconnected"; }
}
catch { Ping_Value.Foreground = Brushes.WhiteSmoke; Ping_Value.Text = "Disconnected"; }
Counter.Content = counter.ToString(); counter++;
};
BackWork_Pinger.RunWorkerAsync();
}
}
}
I wanna make a Pinger that works fine and not freezing my WinForm while disconnected or bad RoundTripTime. Is there any help to make a smooth pinger? or is there any demo project that i can modify from? Thank youuu :)
BackgroundWorker call
DoWorkon parrale thread and callbackProgressChangedon UI thread. In your code, the ping is done onProgressChanged, thus in the UI thread. When the UI thread work, the UI is freezed.To avoid freezing the screen, it is necessary to execute the work on another thread. The ping must be in
DoWork: