On a form with a listbox, progress bar & button...
The background task allows us to continuously update the UI: not having it results in a "flood" of updates towards the end of the process.
Code:private static readonly Random RandomWaitTime = new Random(); private int _iterations; private int _completedIterations; private void button1_Click(object sender, EventArgs e) { if (!int.TryParse(textBox1.Text, out _iterations)) { textBox1.Text = "100"; _iterations = 100; } ResetState(); ResetProgress(); Task.Factory.StartNew(StartLooping); } private void StartLooping() { Parallel.For(0, _iterations, ParallelTask); } private void ParallelTask(int taskId, ParallelLoopState loopState) { WaitForAWhile(); ReportTaskComplete(taskId); } private void ReportTaskComplete(long taskId) { _completedIterations++; if (listBox1.InvokeRequired) listBox1.BeginInvoke((Action) (() => UpdateProgress(taskId))); else UpdateProgress(taskId); } private void UpdateProgress(long completedTaskId) { int newItemIndex = listBox1.Items.Add(completedTaskId.ToString()); listBox1.SelectedIndex = newItemIndex; progressBar1.Value = _completedIterations; } private static void WaitForAWhile() { int waitMillis = RandomWaitTime.Next(501); Thread.Sleep(waitMillis); } private void ResetState() { _completedIterations = 0; listBox1.Items.Clear(); } private void ResetProgress() { progressBar1.Value = 0; progressBar1.Maximum = _iterations; }




Reply With Quote