BackgroundWorker

The BackgroundWorker class allow you to have a responsive UI while you retrieve your data.
For more information, please refer to the Threading > BackgroundWorker page.


using System.Linq; 
using System.Windows.Forms;

namespace MyProject.Forms
{
    public partial class MyForm : Form
    {
        System.ComponentModel.BackgroundWorker _worker = new System.ComponentModel.BackgroundWorker();
        System.Threading.SynchronizationContext _syncContext;

        public MyForm()
        {
            InitializeComponent();
            _syncContext = System.Threading.SynchronizationContext.Current;
        }

        private void MyForm_Load(object sender, System.EventArgs e)
        {
            try
            {
                _worker.WorkerReportsProgress = true;
                _worker.WorkerSupportsCancellation = true;

                _worker.DoWork += new System.ComponentModel.DoWorkEventHandler(HandleDoWork);
                _worker.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(HandleWorkerCompleted);
                _worker.ProgressChanged += new System.ComponentModel.ProgressChangedEventHandler(HandleProgressChanged);

                _worker.RunWorkerAsync();

                this.comboBox1.Items.Add("");

            }
            catch (System.Exception ex)
            {
                ExceptionHandling.MessageShow(System.Reflection.MethodBase.GetCurrentMethod(), ex);
            }
        }

        private void HandleDoWork(
            object sender,
            System.ComponentModel.DoWorkEventArgs e)
        {

            System.Collections.Generic.List<string> companieslist;
            companieslist.Add("one");
            companieslist.Add("two");
            companieslist.Add("three");

            this.comboBox1.Items.Clear();
            for (int i = 0; i < companieslist.Count; i++)
            {
                this.comboBox1.Items.Add(companieslist[i]);
            }

            if (_worker.CancellationPending)
            {
                e.Cancel = true;
            }
        }

        private void HandleProgressChanged(
            object sender,
            System.ComponentModel.ProgressChangedEventArgs e)
        {
            // DO Progress Bar Updates Here

            System.Threading.SendOrPostCallback callback =
                new System.Threading.SendOrPostCallback((o) =>
            {

            });
            _syncContext.Send(callback, null);
        }

        private void HandleWorkerCompleted(
            object sender,
            System.ComponentModel.RunWorkerCompletedEventArgs e)
        {
            // DO Any completed step items here
        }

    }
}


© 2021 Better Solutions Limited. All Rights Reserved. © 2021 Better Solutions Limited TopPrevNext