lock or invoke is better for updating control.

  • Thread starter Thread starter archana
  • Start date Start date
A

archana

Hi all,

I am having application wherein i am using asynchronous programming and
using callback i am updating one label control.

My question is can i use lock statment to lock control. If yes which
one is better to prevent unpredictable update of label. Whether should
i use lock statement or control.invoke and give method name.

Please correct me if i am wrong.

thanks in advance.
 
archana said:
Hi all,

I am having application wherein i am using asynchronous programming and
using callback i am updating one label control.

My question is can i use lock statment to lock control. If yes which
one is better to prevent unpredictable update of label. Whether should
i use lock statement or control.invoke and give method name.

Please correct me if i am wrong.

thanks in advance.

Hi,

You will have to use Control.Invoke. Cross-thread calls to update your UI
are not permitted.

Using Control.Invoke will marshal the call into the UI thread, and so,
updating your label will be safe, since your update method cannot run
side-by-side. Don't use the lock statement.

///
private delegate void SafeUpdateLabelDelegate ( string newText );
private void SafeUpdateLabel ( string newText )
{
myLabel.Text = newText;
}

private void UpdateLabel ( string newText )
{
if ( this.InvokeRequired )
this.Invoke( new SafeUpdateLabelDelegate( SafeUpdateLabel ), newText );
else
SafeUpdateLabel( newText );
}
///

In the above example, calling UpdateLabel will update the label safely, by
either marshalling the call to SafeUpdateLabel to the UI thread (via
this.Invoke) or calling the method directly, if an invoke is not required.
 
archana said:
I am having application wherein i am using asynchronous programming and
using callback i am updating one label control.

My question is can i use lock statment to lock control. If yes which
one is better to prevent unpredictable update of label. Whether should
i use lock statement or control.invoke and give method name.

Please correct me if i am wrong.

Locking would not be sufficient. You *must* update UI components on the
UI thread - there's no reliable alternative.

See http://www.pobox.com/~skeet/csharp/winforms.shtml
 

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

Back
Top