About WPF Multithreads

Published on Tuesday, September 27, 2011

This is a learning notes. We are not going to tell more knowledge about WPF multiple threads, we just give some samples which we practiced.

There are different solutions to implement multiple threads in WPF:

1: The Task:

We firstly introduce the task is because it is recommended in .NET 4, it is a newer tech. The last .NET 4 component for running multithreaded code is provided by System.Threading.Tasks namespace, it is more powerful than other solutions. With the release of .NET 4, Microsoft decided to include the Task Parallel Library in the core of the NET 4.

The main difference between using the Thread object and the Task object available in the System.Threading.Tasks namespace is that the Task object is controlled by the Thread Pool object, so the concurrency and the overall use of resources result in a better product. – from the book WPF 4 in context.

We put a TextBox in XAML:


<Grid Height="192" Width="358">
     <TextBox Height="23" HorizontalAlignment="Left" Margin="124,78,0,0" Name="textBox1" VerticalAlignment="Top" Width="120" />
 </Grid>

We set a task in another thread, here we just let the thread sleep several seconds, then we write something in screen:


private void Window_Loaded(object sender, RoutedEventArgs e)
 {
     Random rand = new Random();

     Task task = new Task(() =>
      {
          //here equals background work for 4 seconds
          Thread.Sleep(4000);

          this.Dispatcher.Invoke(
          new Action(() =>
          {
              this.textBox1.Text = rand.Next().ToString();
          }));
      }
      );
     task.Start();
 }

2: Background Worker:

We use Background worker now. Background worker is said to use real multithread, it use background work, not like Dispatcher, which use actually the same thread but just looks like different thread.


private BackgroundWorker worker;

public Window1() 
{ 
    InitializeComponent(); 
    worker = new BackgroundWorker(); 
    worker.DoWork += new DoWorkEventHandler(worker_DoWork); 
}

void worker_DoWork(object sender, DoWorkEventArgs e) 
{ 
    Random rand = new Random();

    this.textBox1.Dispatcher.Invoke(new Action(() => 
    { 
        //here equals background work for 4 seconds 
        Thread.Sleep(4000);

        this.Dispatcher.Invoke( 
        new Action(() => 
        { 
            this.textBox1.Text = rand.Next().ToString(); 
        })); 
    }));

}

private void Window_Loaded(object sender, RoutedEventArgs e) 
{ 
    worker.RunWorkerAsync(); 
}

3: Thread:

Looks like Task. the code is:


private void Window_Loaded(object sender, RoutedEventArgs e) 
{ 
Random rand = new Random();

Thread thread = new Thread(() => 
{ 
//here equals background work for 4 seconds 
Thread.Sleep(4000);

this.Dispatcher.Invoke( 
new Action(() => 
{ 
this.textBox1.Text = rand.Next().ToString(); 
})); 
} 
); 
thread .Start(); 
}