Wednesday, January 7, 2015

How to Update WPF control from different Thread

Suppose I have a window with 2 label and I will show number's on label from a new thread:

        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
   
       
       
   


Code Behind:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Threading;

namespace ThreadingTest
{
    ///
    /// Interaction logic for MainWindow.xaml
    ///
    public partial class MainWindow : Window
    {
        public delegate void MyDelegate();
        int n;
        int k = 0;
        public MainWindow()
        {
            InitializeComponent();

            Thread t = new Thread(ThreadMethod);
            n = 20;
            t.Start();
           
        }
        public  void ThreadMethod()
        {
            for (int i = 0; i < n; i++)
            {
                Thread.Sleep(1000);
                label1.Dispatcher.BeginInvoke(new MyDelegate(()=>
                {
                    label1.Content = i.ToString();
                }
                 ));
             
            }
        }
    }
}


Note : Here important thing is that we are able to access variable from main thread to child thread but to access control we need to call Dispatcher associated with lable and then need to call BeginInvoke() or Invoke() method of it.

No comments:

Post a Comment

C# Record type: Something to remember while using record types

  Record in c# provide a concise and expressive way to create immutable data types, record is a keyword in c#, we can use this keyword with ...