Software & Finance





Silverlight - Handing UI Elements in Worker Thread





I have given a simple Silverlight application explaining on how to handle UI elements in the worker thread.

System.Threading.Thread is the class you want to use to create a thread. When you instantiate System.Threading.Thread the class you can pass two kinds of delegate.

System.Threading.ThreadStart and System.Threading.ParameterizedThreadStart

 

Here is the sample code:

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Windows;

using System.Windows.Controls;

using System.Threading;

 

 

namespace Multi_Threading_Sample

{

 

   public partial class MainPage : UserControl

   {

     public void TheadFunction ()

      {

         while (true)

         {

            //Do some work if you access any UI elements, it will crash

            Thread.Sleep(50);

         }

      }

 

      public void TheadFunctionSafe()

      {

         while (true)

         {

              this.Dispatcher.BeginInvoke(new Action(

                   delegate()

                   {

                       //Working with UI elements are safe here

                   }

                ));

            Thread.Sleep(50);

         }

      }

 

 

      public MainPage()

      {

         InitializeComponent();

 

         Thread myThread = new Thread(ThreadFunctionSafe);

         myThread.Start();

      }

}