Reputation: 17427
it's possible? I need for example,set new value to an label in thread execution.
I tried this:
private void button1_Click_1(object sender, EventArgs e)
{
Thread th = new Thread(new ThreadStart(DoWork));
th.Start();
}
public void DoWork()
{
while (true)
{
StartSearch(path, ref httpRequest);
}
}
public void StartSearch(string path, ref HttpWebRequest httpRequest) {
foo.GetTopic(path, delegate(string post, string name, string uid)
{
{
if (post.Contains("<font color=\"#0000FF\">"))
{
string msg = string.Format("Post:{0}\r\nby {1}({2})", post, name, uid);
//MessageBox.Show(msg);
labelX.text = msg;
}
}
}
);
}
I'm getting the following error:
Cross-thread operation not valid: Control 'labelX' accessed from a thread other than the thread it was created on.
How I do this? Thanks in advance!
Upvotes: 0
Views: 6117
Reputation: 25
I also had this problem. Eventually solved.
Do not try to do everything in the textbox, but just think about the Msg you want to send to the textbox box.
MY CODE:
private delegate void _deleSetMesssage(string msg);
public void SetMessage(string msg)
{
if (this.InvokeRequired)
{
_deleSetMesssage method = new _deleSetMesssage(SetMessage);
this.Invoke(method, new object[] { msg });
}
else
{
this.label1.Text = msg;
}
}
Not preferred Method:
CheckForIllegalCrossThreadCalls = false;
Upvotes: 0
Reputation: 1
You can use a background worker
. In report progress, change the label value.
Upvotes: -1
Reputation: 60448
You have to invoke it to ensure that the ui thread (the thread who has created your label) does it. Its easy, try the following...
delegate void SetLabel(string msg);
void SetLabelMethod(string msg)
{
labelX.text = msg;
}
this.Invoke(new SetLabel(SetLabelMethod), new object { msg }); // this is your form
Upvotes: 4
Reputation: 18743
Call a delegate in your new thread, using an anonymous method:
this.Invoke((MethodInvoker) delegate {
labelX.Text = msg;
});
Upvotes: 3