[英]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. 我有这样的WPF应用程序。
namespace WpfApplication1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public delegate void NextPrimeDelegate();
int i = 0;
public 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. Parallel.Invoke()
接受一个(可变长度)lambda(内联函数)列表作为其参数。 It invokes/executes all the lambdas in parallel, and blocks execution until execution of all the lambdas are complete. 它并行调用/执行所有lambda,并阻止执行直到所有lambda执行完毕。 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. 在这种情况下,Parallel.Invoke将花费1500毫秒,因为最长的运行函数是第二个函数,该函数等待1500毫秒才返回。
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())
我不太确定您想用示例代码来说明什么,但是如果您想并行运行Start()和Stop()(再次,实际上并不确定为什么),您可以类似于
Parallel.Invoke(tr[0].Start(), tr[0].Stop())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.