I try to build a simple WPF application and have a listbox in the MainWindow.
The background is that it pings some machines but I want that the GUI already opens and whenever the ping finishes, the listbox should update the content.
Let me show my code. MainWindow.xaml.cs
public ObservableCollection<String> LbStatus
{
get { return BL.GetStatus(); }
}
BL.cs
public static ObservableCollection<string> GetStatus()
{
List<string> hostnames = new List<String>(GetHostnames());
ObservableCollection<string> status = new ObservableCollection<string>();
foreach(string hostname in hostnames)
{
Task<string> task = Task.Run(async () => await
PingHost(HM.GetHostname(hostname)));
status.Add(task.Result);
}
return status;
}
static public async Task<string> PingHost(string hostname)
{
Ping x = new Ping();
try
{
PingReply reply = await x.SendPingAsync(hostname, 5000);
if (reply.Status == IPStatus.Success)
{
return "Online";
}
else
return "Offline";
}
catch (Exception excep)
{
//exception handling
}
}
I think the problem is that my program waits for task.result. But in my head, it should just skip and return nothing and whenever it's finished it should return the correct string. But (and that's the whole reason why I do this) the GUI should already start.
I hope my question makes sense and someone can help me with that :-)
Thanks!