主要问题是:如何在后台的多个线程上运行TestingButton_Click中的代码(类似于BackgroundWorker),这样我就能够:
以下代码在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()结构是
do
{
do
{
} while (isSetbCompaundParams);
} while (isSetaCompaundParams);
//filling up results into tables (main window variables) later to be connected to DataGridsTestPairParallel()是用InfinitePartitioner实现的,并且只使用类似的结构和Parallel.ForEach(新的InfinitePartitioner(),...
谢谢你的帮助。
发布于 2011-12-15 01:37:38
如何在后台的多个线程上运行TestingButton_Click中的代码。
我会使用任务,因为它们的设计完全是为了做你想做的事情。
在你接近实际解决方案之前,我唯一要回答的问题是:
报告进度
有很多方法可以报告给定线程的进度,您必须订阅事件,并编写代码来报告线程的进度。为了更新窗体上的控件,这需要您调用更改,这不是一个微不足道的功能。
发布于 2011-12-15 01:31:54
使用.NET 4.0任务,而不是自己创建新的线程。任务为您提供更细粒度的控制,轻松将数据传递到后台操作,并为跨多个并发任务等待结果和在需要时一举取消所有内容提供出色的支持。强烈推荐。
https://stackoverflow.com/questions/8508487
复制相似问题