Monday, August 13, 2012

Access GUI from background thread using C# Forms

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

namespace Threads
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        delegate void SetTextCallback(string text, int value);

        private void Form1_Load(object sender, EventArgs e)
        {
            ThreadTest t = new ThreadTest(this);
            Thread th = new Thread(t.DoWork);
            th.Start();
            //th.Join();
        
        }

        public void Populate(string text, int value)
        {

            if (this.lblMesaj.InvokeRequired)
            {
                SetTextCallback d = new SetTextCallback(Populate);
                this.Invoke(d, new object[] { text,value });
                this.Invoke(d, new object[] { text,value });

            }
            else
            {
                this.lblMesaj.Text = text;
                this.progressBarFinalize.Value = value;
            }

            lblMesaj.Text = text;
        }


        private void btnSave_Click(object sender, EventArgs e)
        {
            this.Close();
        }

    }

    class ThreadTest
    {
        public delegate void populateTextBoxDelegate(string text);
        Form1 formMain;

        public ThreadTest(Form1 form)
        {
            formMain = form;
        }


        public void DoWork()
        {
            for (int i = 0; i < 1000; i++)
            {
                formMain.Populate("In progress ....", i/10);
                for (int j = 0; j < 1000; j++)
                {
                    for (int k = 0; k < 100; k++)
                    {
                        double b = Math.Sqrt(923409290423) / Math.Sqrt(423423);
                    }
                }
            }

            formMain.Populate("Thread has finished!",100);

        }
    }

}

1 comment: