Click here to Skip to main content
11,701,616 members (66,651 online)
Click here to Skip to main content

Tagged as

Wait progress bar for long running UI operations

, 3 Feb 2012 CPOL 5.8K 4
Rate this:
Please Sign up or sign in to vote.
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:
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)

Share

About the Author

Member 147785
Russian Federation Russian Federation
No Biography provided

You may also be interested in...

Comments and Discussions

 
-- There are no messages in this forum --
| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.150819.1 | Last Updated 3 Feb 2012
Article Copyright 2012 by Member 147785
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid