Control.Invoke frustration

O

ORC

It's a bit difficult for me to understand the threading and control.invoking
issue - I can't see what's wrong with the following code and would highly
appreciate any help ( i'm using C#) (error message is included below code):

namespace Application_for_tests
{
public delegate void UpdateFormDelegate();
public class Form1 : System.Windows.Forms.Form
{
private System.Windows.Forms.TextBox textBox1;
private System.Windows.Forms.Button button1;
private TestClass testClass = new TestClass();
System.Threading.Thread thread;
System.Threading.ThreadStart threadDelegate;
public UpdateFormDelegate updateFormDelegate;

private bool threadRunning = false;
public Form1()
{
InitializeComponent();
updateFormDelegate = new UpdateFormDelegate(this.updateForm);
}
protected override void Dispose( bool disposing )
{
base.Dispose( disposing );
}
private void InitializeComponent()
{
this.textBox1 = new System.Windows.Forms.TextBox();
this.button1 = new System.Windows.Forms.Button();
//
// textBox1
//
this.textBox1.Location = new System.Drawing.Point(64, 80);
this.textBox1.Size = new System.Drawing.Size(96, 20);
this.textBox1.Text = "textBox1";
//
// button1
//
this.button1.Location = new System.Drawing.Point(64, 112);
this.button1.Size = new System.Drawing.Size(96, 24);
this.button1.Text = "button1";
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// Form1
//
this.Controls.Add(this.button1);
this.Controls.Add(this.textBox1);
this.MinimizeBox = false;
this.Text = "Form1";
}

static void Main()
{
Application.Run(new Form1());
}
private void button1_Click(object sender, System.EventArgs e)
{
if (!threadRunning)
{
threadDelegate = new System.Threading.ThreadStart(threadFunction);
thread = new System.Threading.Thread(threadDelegate);
thread.Start();
threadRunning = true;
}
}
private void threadFunction()
{
this.Invoke(this.updateFormDelegate);
MessageBox.Show("thread will finish now!");
threadRunning = false;
}

private void updateForm()
{
textBox1.Text = "some text";
}
}
}
******************************************************
An error occurs in the line "this.Invoke(this.updateFormDelegate);" with
following message: "An unhandled exception of type
'System.ArgumentException' occurred in System.Windows.Forms.dll"
"Additional information: ArgumentException".

Thanks,
Ole
 
D

Daniel Moth

1. You cannot pass any delegate you want to Invoke; rather, you can only
use the EventHandler.

Cheers
Daniel
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top