I have been struggling to get a toolbar to update its progress information from an event raised ina parallel for loop. I have tried using delegates to get it to work but it just hangs after about the iteration.
The code that replicates the problem is below. It s just a windows form with a toolstrip and a toolstripprogressbar with a button to start the test.
I am relativly new to multi threading but in all the examples i have tried from various sources on the net I cannot get this to work.
Expand|Select|Wrap|Line Numbers
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Data;
- using System.Drawing;
- using System.Linq;
- using System.Text;
- using System.Windows.Forms;
- using System.Threading;
- namespace WindowsFormsApplication1
- {
- public partial class Form1 : Form
- {
- delegate void ProgressDelegate(int progress);
- public Form1()
- {
- InitializeComponent();
- // A nasty HACK but the delegate method invocation seems to be recursive and not work.
- //Control.CheckForIllegalCrossThreadCalls = false;
- }
- private void button1_Click(object sender, EventArgs e)
- {
- Class1 test = new Class1();
- test.progress += new EventHandler<ProgressArgs>(test_progress);
- test.DoWork();
- this.toolStripProgressBar1.Value = 0; // reset
- }
- void test_progress(object sender, ProgressArgs e)
- {
- //if (e.ProgressValue>this.toolStripProgressBar1.Value)
- // this.toolStripProgressBar1.Value = e.ProgressValue;
- SetProgress(e.ProgressValue);
- }
- public void SetProgress(int progress)
- {
- if (this.InvokeRequired)
- {
- ProgressDelegate d = new ProgressDelegate(SetProgress);
- this.Invoke(d, new object[] { progress });
- }
- else
- {
- this.toolStripProgressBar1.Value = progress;
- }
- }
- }
- class Class1
- {
- public event EventHandler<ProgressArgs> progress;
- public void DoWork()
- {
- Parallel.For(0, 100, i =>
- {
- Thread.Sleep(25);
- this.progress(this, new ProgressArgs(i));
- });
- }
- }
- class ProgressArgs : EventArgs
- {
- int _progressvalue = 0;
- public ProgressArgs(int progressvalue)
- {
- _progressvalue = progressvalue;
- }
- public int ProgressValue
- {
- get
- {
- return _progressvalue;
- }
- set
- {
- _progressvalue = value;
- }
- }
- }
- }