开发者

Multithreading WPF Application Question

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;

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 开发者_如何学Pythonis working without problem.My question is:I want to call more than a function that is called CheckNextNumber. For example:I have to make something like this.

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


For C# version prior to 3.0 you can use anonymous delegates:

 Dispatcher.BeginInvoke(DispatcherPriority.Normal, (NextPrimeDelegate)delegate()
 { 
    tr[0].Start();
    tr[0].Stop(); 
 });

Beginning with C# 3.0 you can use lambdas (which is basically syntactic sugar on top of anonymous delegates). Additionally you don't need your NextPrimeDelegate because .NET 3.5 introduced the generic parameterless Action delegate.

 Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(() =>
 { 
    tr[0].Start();
    tr[0].Stop(); 
 });


Instead of using a delegate, you can use an Action with a codeblock with whatever code you like, e.g:

   Dispatcher.BeginInvoke(
      DispatcherPriority.Normal,
      new Action(() =>
      {
          tr[0].Start();
          tr[0].Stop();
      }));
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜