在后台并行运行

本文关键字:运行 并行 后台 | 更新日期: 2023-09-27 18:17:56

主要问题是:如何在TestingButton_Click中运行代码在后台的几个线程(类似于BackgroundWorker),所以我将能够:
1. 将所有原始数据获取到方法
2. 同时取消所有线程的测试
3.
报告进展4. 将所有结果表检索到主线程。

以下代码位于TestingButton_Click 中
List<Thread> threads = new List<Thread>();
            //Testing for each pair
            foreach (InterfaceWithClassName aCompound in Group1)
            {
                foreach (InterfaceWithClassName bCompound in Group2)
                {
                    InstancePair pair = new InstancePair();
                    //some code
                    if (testModeParallel)
                    {
                        Thread thr = new Thread(TestPairParallel);
                        thr.Start(pair);
                        threads.Add(thr);
                    }
                    else
                    {
                        Thread thr = new Thread(TestPairSerial);
                        thr.Start(pair);
                        threads.Add(thr);
                    }
                }
            }              
            while (true)
            {
                int i = 0;
                foreach (Thread thread in threads)
                {
                    if (thread.IsAlive)
                        break;
                    i++;
                }
                if (i == threads.Count)
                    break;
                Thread.Sleep(1000);
            }
            pairsResultsDataGrid.ItemsSource = tab.DefaultView

用户可以选择要测试的化合物,所以每次我都有不同数量的对要测试。为了以防万一,我使用了不同的方法TestPairSerial()和TestPairParallel()。

TestPairSerial() structure is

        do
        {
            do
            {
            } while (isSetbCompaundParams);
        } while (isSetaCompaundParams);
        //filling up results into tables (main window variables) later to be connected to DataGrids

TestPairParallel()是用InfinitePartitioner实现的,并且只在Parallel中使用类似的结构。ForEach(新InfinitePartitioner(),…

谢谢你的帮助。

在后台并行运行

使用。net 4.0 Tasks代替自己创建新的thread。任务为您提供了更细粒度的控制,使将数据传递到后台操作变得容易,并为跨多个并发任务等待结果以及在需要时一举取消所有内容提供了出色的支持。强烈推荐。

如何在TestingButton_Click中的几个线程上运行代码背景。

我会使用任务,因为它们的设计正是为了做你想做的事情。

在你接近实际解决方案之前,我要回答的唯一一个问题是:

报告进展
有很多方法可以报告给定线程的进度,您必须订阅一个事件,并编写代码来报告线程的进度。为了更新表单上的控件,这需要调用更改,这不是一个微不足道的特性。