MaxCoder88
MaxCoder88

Reputation: 2428

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 is 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(); 

Upvotes: 1

Views: 225

Answers (2)

bitbonk
bitbonk

Reputation: 49619

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(); 
 });

Upvotes: 2

Tim Lloyd
Tim Lloyd

Reputation: 38444

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();
      }));

Upvotes: 2

Related Questions