archana wrote:
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.
--
Hope this helps,
Tom Spink
Google first, ask later.