Wait progress bar for long running UI operations





5.00/5 (1 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;
}