Reputation: 2904
Dot Net Version = 4. Language = C#
I am pretty much a novice in c# so please consider me a beginner :).
What i am trying to do: Create a WPF app that displays computer uptime information in a datagrid Get computernames from a listbox and run a "Ping" function using TPL which returns a status property indicating whether the computer was alive or unreachable.
If the status property from a task returned "success" then i would run an "uptime" function to get the uptime from the server and add it to an observable collection which will serve as input to a datagrid.
I am currently having trouble running the second task that is - "Uptime" function which seems to be freezing the UI. I am not sure if i should be running the "uptime" function inside a "continuewith" block. Also i would like to be able to cancel out of all operations when required.
CODE:
private void btn_Uptime_Click(object sender, RoutedEventArgs e)
{
List<Task> tasks = new List<Task>();
tokenSource = new CancellationTokenSource();
var ui = TaskScheduler.FromCurrentSynchronizationContext();
foreach (var item in Listbox1.Items)
{
string host = item.ToString();
// Start Parallel execution of tasks
var compute = Task.Factory.StartNew(() =>
{
return PingHost(host);
}, tokenSource.Token);
tasks.Add(compute);
if(compute.Result.Status.ToLower() == "success")
{
//Need to run the getuptime function based on the "success" result from each compute task
//without freeqing the UI.
WMIHelper.GetUptime(compute.Result.ComputerName);
}
}
Upvotes: 2
Views: 432
Reputation: 12295
Try this
......
tasks.Add(compute);
compute.ContinueWith(c=>
{
if(c.Result.Status.ToLower() == "success")
Dispatcher.Invoke(()=>WMIHelper.GetUptime(compute.Result.ComputerName));
});
Upvotes: 1