Karthiga Nadashan
Karthiga Nadashan

Reputation: 35

Cross-thread operation

I’m doing some stuffs in thread and I’m try to access the label property, but I can’t to set the property value.

lblDisplay.Visible = true;

I’m getting an error on this. Error - Cross-thread operation not valid: Control 'lblDisplay' accessed from a thread other than the thread it was created on. Thanks in advance.

Upvotes: 0

Views: 285

Answers (5)

Suvabrata Roy
Suvabrata Roy

Reputation: 121

I think you first need to Check whether its need to invoke or not ( In some other case that same code may not need to invoke) so...

if(lblDisplay.InvokeRequired) {
 lblDisplay.Invoke((Action)delegate{ lblDisplay.Visible = true; }); // For synchronous
 lblDisplay.BeginInvoke((Action)delegate{ lblDisplay.Visible = true; }) // For asynchronous
      }
else
{
lblDisplay.Visible=true;
}

Upvotes: 1

user4399732
user4399732

Reputation:

Using this.BeginInvoke method with lambda :

this.BeginInvoke(new Action(() => { lblDisplay.Visible = true; }));

Reference : https://msdn.microsoft.com/en-us/library/system.windows.forms.control.begininvoke(v=vs.110).aspx

Upvotes: 0

Sudharshan
Sudharshan

Reputation: 348

You can’t directly access from a thread other than the thread it was created on. You can set that property value by using MethodInvoker.

lblDisplay.Invoke((MethodInvoker)(() => { lblDisplay.Visible = true; }));

This the way you need to access the control in different thread.

Upvotes: 0

Prime
Prime

Reputation: 2482

You should use the BeginInvoke method on the form to set the variable on the same thread it's running on, for example:

this.BeginInvoke((Action)delegate{ lblDisplay.Visible = true; });

Most people will tell you to use the Invoke method instead but unless you absolutely NEED everything in the delegate to be run before any other code in the thread is executed you probably wont need it. Invoke will block the thread from processing any further until the delegate has completed, where as BeginInvoke will simply execute it in the thread the form is running in while simultaneously running the thread that began the invoke.

Upvotes: 2

A Coder
A Coder

Reputation: 3046

A Control can only be accessed within the thread that created it - the UI thread.

Try this,

Invoke(new Action(() =>
{
    lblDisplay.Visible = true;
}));

Upvotes: 0

Related Questions