The problem is your DispatchTimer. You should use async/await , delegates or create a new thread to run the update asynchronous.
Ping verify internet connection blocks UI
Kran2022
381
Reputation points
Hi All:
In my WPF app, during the app launch detects static ip address as bleow, the UI is freezing. Could you please someone tell me what is the mistake? thanks
My app should verify if there is an internet connection in the system for every x seconds, Yes: Green, No:Red color
Static IP: 192.168.192.91, Subnet:255.255.255.0 Def Gateway:192.168.192.90, DNS: 12.12.8.8
private void Window_Loaded(object sender, RoutedEventArgs e)
{
BackgroundAsyncTasksTimer = new DispatcherTimer();
BackgroundAsyncTasksTimer.Interval = TimeSpan.FromMilliseconds(2000);
BackgroundAsyncTasksTimer.Tick += BackgroundAsyncTasksTimer_Tick;
BackgroundAsyncTasksTimer.Start();
}
private async void BackgroundAsyncTasksTimer_Tick(object sender, object e)
{
bool details = await IsWebsiteUp_Ping("https://stackoverflow.com/");
if (details)
{
einternetcoxn.Fill = (SolidColorBrush)new BrushConverter().ConvertFromString("#00ff00");
}
else
{
einternetcoxn.Fill = (SolidColorBrush)new BrushConverter().ConvertFromString("#841c34");
}
}
public static async Task<bool> PingAsync(string host)
{
try
{
var ping = new System.Net.NetworkInformation.Ping();
var reply = await ping.SendPingAsync(host);
return (reply.Status == System.Net.NetworkInformation.IPStatus.Success);
}
catch { return false; }
}
private async Task<bool> IsWebsiteUp_Ping(string url)
{
Ping ping = new Ping();
var hostName = new Uri(url).Host;
PingReply result = await ping.SendPingAsync(hostName);
return result.Status == IPStatus.Success;
}
Accepted answer
1 additional answer
Sort by: Most helpful
-
Bruce (SqlWork.com) 55,686 Reputation points
2022-11-24T16:51:15.017+00:00 The point of DispatchTime is that it run on the UI thread. You should run the ping on a separate thread, and on completion dispatch to the ui thread to do the ui update.