将一段代码放在不同的线程上?

时间:2010-12-07 07:44:51

标签: c# multithreading

我提前感谢您的帮助。我对编程很新,所以对我很轻松。现在我有一个耗时的循环,我真的需要在UI线程之外运行,因为Update()更新了一个进度条,直到这个循环完成才会发生。我查看了一些简短的线程教程,并且在大循环结束之前,更新永远不会呈现。

private void Button_Convert_Click(object sender, RoutedEventArgs e)
{
 MachineAngleCalculations.Instance.Arm1Length_Arbitrary = 12;
 MachineAngleCalculations.Instance.Arm2Length_Arbitrary = 11;

 int resolution = 100000; //points per shape
 double xstep, ystep, x, y;

 int totalpoints = resolution * ShapeList.Count;
 int calculatedpoints = 0;
 ProgStat.Update(calculatedpoints, totalpoints, "Calculated", "individual instructions.");

 InstructionList.Clear();

 foreach (MachineLine item in ShapeList)
 {
  xstep = (item.End.X - item.Start.X) / (resolution - 1);
  ystep = (item.End.Y - item.Start.Y) / (resolution - 1);

  for (int i = 0; i < resolution; i++)
  {
   x = item.Start.X + xstep * i;
   y = item.Start.Y + ystep * i;
   InstructionList.Add(MachineAngleCalculations.Instance.XYtoMachineInstrution(x, y, 1));
   calculatedpoints += 1;
   ProgStat.Update(calculatedpoints, totalpoints, "Calculated", "individual instructions.");
  }
 }
}

那么在不同的线程上执行foreach循环的最简单方法是什么? 有没有办法在没有将其放入不同功能的情况下这样做?

2 个答案:

答案 0 :(得分:1)

您可以尝试:

异步编程

Asynchronous Method Invocation(有史以来最好的教程!!)

后台工作者

BackgroundWorker Class Sample for Beginners

答案 1 :(得分:0)

简单的解决方案将使用BackgroundWorker Class