Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / desktop / WinForms

Wait progress bar for long running UI operations

5.00/5 (1 vote)
3 Feb 2012CPOL 14.5K  
Hello!Here is a small article - Show progress on long-running operations, which describes approach to keep the UI responsive, starting long-running operations in separate thread. This approach is native and without any 3d-party libraries and even without BackgroundWorker.For example, the...
Hello!

Here is a small article - Show progress on long-running operations, which describes approach to keep the UI responsive, starting long-running operations in separate thread. This approach is native and without any 3d-party libraries and even without BackgroundWorker.

For example, the code below is sample simulates a treatment of group of files:
C#
private void startBtn_Click(object sender, EventArgs e)
{
    // the array of file paths
    string[] filePaths = ...

    UpdateProgressBar(0);           

    // start lengthy task in separate thread
    ThreadPool.QueueUserWorkItem(new WaitCallback(new Action<object>(delegate(object state)
    {
        DoSomethingWithFiles(filePaths);
    })));
}

private void DoSomethingWithFiles(string[] filePaths)
{
    for (int i = 0; i < filePaths.Length; i++)
    {
        string fileText = File.ReadAllText(filePaths[i]);

        // do something with the read file content
        ...

        // set refreshed value to ProgressBar
        UpdateProgressBar((i + 1) * 100 / filePaths.Length);
    }

    // set refreshed value to ProgressBar
    UpdateProgressBar(100);
}

private void UpdateProgressBar(int currentValue)
{
    // if it's UI thread, simply update ProgressBar as usual.
    // Otherwise, make the current method be called in UI thread.
    if (progressBar1.InvokeRequired)
        progressBar1.BeginInvoke(new Action(delegate() { UpdateProgressBar(currentValue); }));
    else
        progressBar1.Value = currentValue;
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)