Thursday 2 January 2014

Access the Controls inside the Thread - Winforms

In this article we are going to see how to update the controls in the Thread, because when you try to update the value or change the value or try to access the control in the Thread , it will return back cross thread operation or Invalid operation exception.

To access the controls inside the thread we have to use the Delagates, which will use to invoke a Method having same signature of delegates.

To access the controls inside the thread, we can go for another process called background worker in which we can access the controls in the report progress

Let we some sample we have a Listview and a button, on button click we have to start a thread and do some operation , after a some particular time i need to add some values to the listview.

Code: Delegate

        public delegate void UpdateView(object sender);

        public void Update(object sender)
        {
           
            var f = listView1.Items.Add("Text");
            f.SubItems.Add("1");
            f.SubItems.Add("2");
        }

        private void CallThread()
        {
            UpdateView view = new UpdateView(Update);           
            listView1.BeginInvoke(view,new object[]{this});
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Thread th = new Thread(CallThread);
            th.Start();
        }


 Code BackgroundWorker
     In background worker we are creating a method which will do the process and then when ever we requires to update anything we have to invoke a report progress where we can write code for access the controls present in the UI. first parameter specify the percentage and the second parameter specify the any values that need to be passed from the method to the report progress , this will use in update the progress bar while running a long run process.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        BackgroundWorker worker = new BackgroundWorker();

        public Form1()
        {
            InitializeComponent();
            worker.WorkerReportsProgress = true;
            worker.WorkerSupportsCancellation = true;
            worker.DoWork += new DoWorkEventHandler(worker_DoWork);
            worker.ProgressChanged += new ProgressChangedEventHandler(worker_ProgressChanged);
            worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted);
        }

        void LoadValues()
        {
            for (int i = 0; i < 10; i++)
            {
                Thread.Sleep(1000);
                if (i % 2 == 0)
                {
                    worker.ReportProgress(i, null);
                }
            }
        }

        void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            listView1.Items.Add("Completed");
        }

        void worker_DoWork(object sender, DoWorkEventArgs e)
        {
            LoadValues();
        }

        void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            listView1.Items.Add(e.ProgressPercentage.ToString());
        }

        private void Form1_Load(object sender, EventArgs e)
        {
           
        }

        private void button1_Click(object sender, EventArgs e)
        {
            worker.RunWorkerAsync();
        }
    }
}

 Output:





From this article you can learn how to access the controls inside the thread operation.

No comments:

Post a Comment