Click here to Skip to main content
15,886,095 members
Articles / Desktop Programming / Windows Forms
Alternative
Tip/Trick

Wait progress bar for long running UI operations

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
3 Feb 2012CPOL 14.2K   4   1
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)


Written By
Russian Federation Russian Federation
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
Questiontasks Pin
kiquenet.com20-Dec-19 21:49
professionalkiquenet.com20-Dec-19 21:49 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.