Page view counter

Silverlight Tips of the Day - Blog by Mike Snow

Game Programming with Silverlight

Silverlight Tip of the Day #73 - Threading in Silverlight

Threads are used to run multiple jobs concurrently within the same application. In a computer with a single processor, threads are time sliced and the processor will switch between the threads being run. In a computer with two or more processors, threads are able to run at the exact same time, one on each processor.

Using threads in your Silverlight application can improve performance by increasing the responsiveness of your application. The following is a straight forward example of using threads. In this example I have:

  1. Added three TextBlocks in Page.xaml. Each TextBlock will be updated by a separate thread.
  2. Added a Button to toggle starting and stopping the threads.
  3. Declared three threads. Each thread will update their own TextBlock.
  4. Declared a counter for each thread that will show the number of times the thread was run.
  5. Added a Sleep(100) to each thread. You need to sleep some amount of time in your threads or the app will lock up.
  6. Called BeginInvoke on any element I want to update, in this case our TextBlock. This call is required since we are trying to make a change to a UI element that belongs to another thread (the main thread). 
  7. In App.xaml.cs, we set Page.Done = true in the Application_Exit event. This way the threads will quit when the browser is closed.

Preview:

App.xaml:

private void Application_Exit(object sender, EventArgs e)
{
    ((Page)this.RootVisual).Done = true;            
}

Page.xaml:

<UserControl x:Class="Threading.Page"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    Width="400" Height="300">
    <Grid x:Name="LayoutRoot" Background="Yellow">
        <Canvas Margin="50">
            <Button Click="Button_Click" Content="Toggle Threads"></Button>
            <TextBlock x:Name="Data1" Canvas.Top="50">Thread 1</TextBlock>
            <TextBlock x:Name="Data2" Canvas.Top="100">Thread 2</TextBlock>
            <TextBlock x:Name="Data3" Canvas.Top="150">Thread 3</TextBlock>
        </Canvas>
    </Grid>
</UserControl>

Page.xaml.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Threading;
 
namespace Threading
{
    public partial class Page : UserControl
    {
        private Thread _thread1;
        private Thread _thread2;
        private Thread _thread3;
 
        private static System.Windows.Controls.TextBlock _data1;
        private static System.Windows.Controls.TextBlock _data2;
        private static System.Windows.Controls.TextBlock _data3;
 
        private static int _count1 = 0;
        private static int _count2 = 0;
        private static int _count3 = 0;
 
        private static bool _done = true;
 
        public bool Done
        {
            get { return _done; }
            set { _done = value; }
        }
 
        public Page()
        {
            InitializeComponent();
            
            _data1 = Data1;
            _data2 = Data2;
            _data3 = Data3;
        }
 
        private void StartThreads()
        {
            _done = false;
 
            _thread1 = new Thread(DoThread1);
            _thread1.Start();
 
            _thread2 = new Thread(DoThread2);
            _thread2.Start();
 
            _thread3 = new Thread(DoThread3);
            _thread3.Start();      
        }
 
        public static void DoThread1()
        {
            while (!_done)
            {
                _count1++;
                _data1.Dispatcher.BeginInvoke(delegate()
                {
                    _data1.Text = _count1.ToString();
                 
                });
                System.Threading.Thread.Sleep(100);
            }
        }
 
        public static void DoThread2()
        {
            while (!_done)
            {
                _count2++;
                _data2.Dispatcher.BeginInvoke(delegate()
                {
                    _data2.Text = _count2.ToString();
                   
                });
                System.Threading.Thread.Sleep(100);
            }
        }
 
        public static void DoThread3()
        {
            while (!_done)
            {
                _count3++;
                _data3.Dispatcher.BeginInvoke(delegate()
                {
                    _data3.Text = _count3.ToString();
                    
                });
                System.Threading.Thread.Sleep(100);
            }
        }
 
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            if (false == _done)
                _done = true;
            else
                StartThreads();  
        }
 
    }
}

Thank you,
--Mike Snow

 Subscribe in a reader

Comments

Microsoft Weblogs said:

Threads are used to run multiple jobs concurrently within the same application. In a computer with a

# November 25, 2008 5:07 PM

Tip of the Day - Pages, Threading und Monitoring at Programming with Silverlight, WPF & .NET said:

Pingback from  Tip of the Day - Pages, Threading und Monitoring at Programming with Silverlight, WPF &amp; .NET

# November 26, 2008 3:33 AM

Tip of the Day - Pages, Threading und Monitoring at Programming with Silverlight, WPF & .NET said:

Pingback from  Tip of the Day - Pages, Threading und Monitoring at Programming with Silverlight, WPF &amp; .NET

# November 26, 2008 3:33 AM

Matze177 said:

Is the use of "BeginInvoke" instead of "Invoke" in the sample correct?

In Windows.Forms "BeginInvoke" causes the execution of the "Invoke" in another thread. Concerning the sample, this would mean that the thread uses another thread to invoke a method on the main thread.

In Windows.Forms "Invoke" would be sufficient.

# November 26, 2008 3:53 AM

2008 November 26 - Links for today « My (almost) Daily Links said:

Pingback from  2008 November 26 - Links for today &laquo; My (almost) Daily Links

# November 26, 2008 4:03 AM

Dew Drop - November 26, 2008 | Alvin Ashcraft's Morning Dew said:

Pingback from  Dew Drop - November 26, 2008 | Alvin Ashcraft's Morning Dew

# November 26, 2008 11:25 AM

Community Blogs said:

Happy Thanksgiving everyone! In this issue: Martin Mihaylov, Tim Heuer, Katrien De Graeve, Expression

# November 27, 2008 2:33 PM

Silverlight Tips of the Day - Blog by Mike Snow said:

The purpose of this post is to create an outline summary all the blogs from my Silverlight tips of the

# January 2, 2009 5:57 PM

Silverlight Tips of the Day - Blog by Mike Snow said:

The purpose of this post is to create an outline summary all the blogs from my Silverlight tips of the

# January 2, 2009 5:57 PM

o UAU nosso de cada dia said:

essa lista eu copiei desse blog bárbaro (acompanhe por RSS você também): uma lista de dicas super úteis

# January 3, 2009 6:26 AM

Visual Web Developer Team Blog said:

This link provides a complete Tips of the Day Summary Outline - silverlight.net/.../silverlight-tips-of-the-day-summary-outline.aspx

# January 8, 2009 6:37 PM