Pattern - Form OnAction


Open Visual Studio and create a new Project
Find "Windows Forms App" (with C#) and press Next
Change the Project Name to ""
Change the Location by clicking on the Browse button
SS
This will create a solution that contains two projects


In this approach, instead of creating the plain old thread and using delegate to update the UI, we have BackgroundWorker component which does the work for us.
It supports multiple events to run long running process (DoWork), update the UI (ProgressChanged) and you will know when the background thread has actually ended (RunWorkerCompleted).
In the plain old thread, knowing the end of the thread is tricky and you have to rely either of Thread. Join or use some other wait handles.


public partial class UsingBackgroundWorker : Form { 
    BackgroundWorker workerThread = null;

    bool _keepRunning = false;

    public UsingBackgroundWorker()
    {
        InitializeComponent();
        InstantiateWorkerThread();
    }

    private void InstantiateWorkerThread()
    {
        workerThread = new BackgroundWorker();
        workerThread.ProgressChanged += WorkerThread_ProgressChanged;
        workerThread.DoWork += WorkerThread_DoWork;
        workerThread.RunWorkerCompleted += WorkerThread_RunWorkerCompleted;
        workerThread.WorkerReportsProgress = true;
        workerThread.WorkerSupportsCancellation = true;
    }

    private void WorkerThread_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
        lblStopWatch.Text = e.UserState.ToString();
    }

    private void WorkerThread_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        if(e.Cancelled)
        {
            lblStopWatch.Text = "Cancelled";
        }
        else
        {
            lblStopWatch.Text = "Stopped";
        }
    }

    private void WorkerThread_DoWork(object sender, DoWorkEventArgs e)
    {
        System.DateTime startTime = DateTime.Now;

        _keepRunning = true;

        while (_keepRunning)
        {
            Thread.Sleep(1000);

            string timeElapsedInstring = (DateTime.Now - startTime).ToString(@"hh\:mm\:ss");

            workerThread.ReportProgress(0, timeElapsedInstring);

            if(workerThread.CancellationPending)
            {
                // this is important as it set the cancelled property of RunWorkerCompletedEventArgs to true
                e.Cancel = true;
                break;
            }
        }
    }

    private void btnStart_Click(object sender, EventArgs e)
    {
        workerThread.RunWorkerAsync();
    }

    private void btnStop_Click(object sender, EventArgs e)
    {
        _keepRunning = false;
    }

    private void btnCancel_Click(object sender, EventArgs e)
    {
        workerThread.CancelAsync();
    }
}



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