I sugest you take a different tact.
What I typically do for managing thread messages is I create a simple EventArgs class to hold the message information, a Delegate to represent the main thread method that will use the information, and an eventhandler in the main thread that can be assigned to an event in the thread.
So to start, build a simple EventArgs class
public class ProgressEventArgs : EventArgs
{
private int _maxValue = 100;
private int _value = 0;
private string _text = string.Empty;
public int MaxValue
{
get { return _maxValue; }
}
public int Value
{
get { return _value; }
}
public string Text
{
get { return _text; }
}
public ProgressEventArgs(string text, int value, int maxValue)
{
_text = text;
_value = value;
_maxValue = maxValue;
}
public override string ToString()
{
return _text;
}
}
Now create a public delegate. Typically I have a constants.cs file where I create all of my constants, and then outside of the constants class, but in the same name space, I create my delegates like this:
namespace MyNameSpace
{
public delegate void ProgressEvent(object sender, ProgressEventArgs e);
public class Constants
{
}
}
OR you can just add the delegate to the main form.
Next you want to create the method that will receive the event, and process the information (in the main form)
public void SetProgressEvent(object sender, ProgressEventArgs e)
{
if( label1.InvokeRequired )
{
ProgressEvent d = new ProgressEvent(SetProgressEvent);
this.Invoke(d, new object[] { sender, e });
}
else
{
progressBar1.Maximum = e.MaxValue;
progressBar1.Value = e.Value;
label1.Text = e.Text;
}
}
Okay, now you want to assign the event to this method. You can do this in the main constructor of your form if this is also where your thread is living. If the thread is in a sperate file or class, then you will declare the event in that class, and attach it from the main form.
onProgressEvent +=new ProgressEvent(SetProgressEvent);
Now inside the thread, you can check to see if the event handler is assigned, and if so send the data to it.
// INSIDE THE THREAD
if(onProgressEvent != null)
{
for(int i=1;i<=100;i++)
{
onProgressEvent(this, new ProgressEventArgs(
i.ToString()+" % completed"
, i
, 100));
System.Threading.Thread.Sleep(20);
}
}
The key to inter thread communication when a Component is involved (or any non thread safe object) is to perform the Invoke as you can see in the SetProgressEvent method.
Hope this help,
// Jerry