Software & Finance





WPF - Handing UI Elements in Worker Thread





I have given a simple WPF 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 Window1 : Window

   {

     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.Invoke(

             System.Windows.Threading.DispatcherPriority.Normal,

             new Action(

               delegate()

               {

                  //Working with UI elements are safe here

               }

           ));

            Thread.Sleep(50);

         }

      }

 

 

      public Window1()

      {

         InitializeComponent();

 

         Thread myThread = new Thread(ThreadFunctionSafe);

         myThread.Start();

      }

}