开发者

How can I use parallel programming to call more than one function at a time by using Parallel Invoke?

I have a WPF application like this.

namespace WpfApplication1
{
 /// <summary>
/// Interaction logic for MainWindow.xaml
 /// </summary>
 public partial class MainWindow : Window
 {
public delegate void NextPrimeDelegate();
int i = 0;

开发者_StackOverflowpublic MainWindow()
{
  InitializeComponent();
}

 public void CheckNextNumber()
{
  i++;
  textBox1.Text= i.ToString();
    Dispatcher.BeginInvoke(
      System.Windows.Threading.DispatcherPriority.SystemIdle,
      new NextPrimeDelegate(this.CheckNextNumber));

 }

private void button1_Click(object sender, RoutedEventArgs e)
{
  Dispatcher.BeginInvoke(
      DispatcherPriority.Normal,
      new NextPrimeDelegate(CheckNextNumber));
  }
 }

Above code is working without problem.My question is:How can I use parallel programming to call more than one function at a time by using Parallel Invoke?

For example:I have to make something like this.

tr[0].Start();
tr[0].Stop(); 


I can't quite connect your attached code sample with your question, but I'll answer your question. Parallel.Invoke() takes in a (variable-length) list of lambdas (inline functions) as its parameters. It invokes/executes all the lambdas in parallel, and blocks execution until execution of all the lambdas are complete. For example:

Parallel.Invoke( () => Thread.Sleep(500), () => Thread.Sleep(1500), () => Thread.Sleep(200));

This would invoke all three of those functions at once (() => ... is a function declared inline that takes no parameters and returns the result of the single expression that comes afterwards.) and block (meaning that execution will not continue past that point on the caller's thread) until all three of those functions are finished exeucting. In this case, Parallel.Invoke will take 1500 milliseconds, since the longest running function is the second one, which waits for 1500 milliseconds before returning.

I'm not quite sure what you are trying to illustrate with your example code, but if you'd like to run Start() and Stop() in parallel (again, don't really see why you would), you can do something like Parallel.Invoke(tr[0].Start(), tr[0].Stop())

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜