任务并行库 - 运行相关任务

时间:2014-08-05 18:22:10

标签: wpf c#-4.0 task-parallel-library

Dot Net Version = 4。 语言= C#

我几乎是c#的新手,所以请认为我是初学者:)。

我想做什么: 创建一个WPF应用程序,在数据网格中显示计算机正常运行时间信息 从列表框中获取计算机名并使用TPL运行“Ping”函数,该函数返回一个状态属性,指示计算机是处于活动状态还是无法访问。

如果任务的status属性返回“success”,那么我将运行一个“uptime”函数来从服务器获取正常运行时间并将其添加到一个可观察的集合中,该集合将作为数据网格的输入。

我目前无法运行第二项任务 - “正常运行时间”功能,似乎冻结了用户界面。我不确定我是否应该在“continuewith”块中运行“uptime”功能。 此外,我希望能够在需要时取消所有操作。

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); 
            }
     }

1 个答案:

答案 0 :(得分:0)

试试这个

       ......
        tasks.Add(compute);
        compute.ContinueWith(c=>
        {
            if(c.Result.Status.ToLower() == "success")
            Dispatcher.Invoke(()=>WMIHelper.GetUptime(compute.Result.ComputerName));
        });
相关问题