2011-12-14 149 views
0

主要问题是:如何在后台(类似于BackgroundWorker的)几个线程运行中TestingButton_Click的代码,所以我将能够:
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()结构是

 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(),...

谢谢您的帮助。

+1

你的问题到底是什么。你的第一句话没有意义。提出一个问题。我建议您丢失背景信息,因为它与您当前的问题无关。 – 2011-12-14 17:09:25

+0

查看[任务](http://msdn.microsoft.com/en-us/library/dd537609.aspx)类 – oleksii 2011-12-14 17:17:12

+0

请选择一个问题,然后仅发布与该问题相关的信息。 – Gabe 2011-12-14 17:17:32

回答

1

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

我会使用任务,因为他们被设计为做你想要的。

唯一的其他问题,我会回答,直到你得到更接近实际的解决方案是:

报告进度

有很多的方式来回报给定线程的进展,你将不得不订阅一个事件,并编写代码来报告线程的进度。为了更新窗体上的控件,这将需要您调用更改,这不是一个简单的功能。

2

使用.NET 4.0的任务,而不是自己创建新线程。任务给你控制的粒度更细,可以很容易将数据传递到后台运行,并等待整个亩成果提供了极好的支持如果需要,可以一次性执行并发任务并取消一切。强烈推荐。