Calling Control.Invoke to Update UI Elements

Started by thiruvasagamani, Jun 02, 2009, 07:18 PM

Previous topic - Next topic

thiruvasagamani

Calling Control.Invoke to Update UI Elements

Since the code is currently executing in the socket's thread, Control.Invoke must be called if user interface elements will be updated. The full framework supports the two Invoke methods listed below. However, the .NET Compact Framework only supports the first Invoke method; it does not support the second method that passes a list of arguments to the delegate.

C#
Copy Code

public object Invoke(Delegate);
public object Invoke(Delegate, object[]);

VB.NET
Copy Code

Public Function Invoke(Delegate) As Object
Public Function Invoke(Delegate, Object()) As Object

So the arguments are saved to class fields and a synchronization object controls access to the block of code that uses the fields. You can use the Threading.Monitor class to synchronize access to a block of code, or use the lock statement in C# or SyncLock statement in VB.NET (they both use the Monitor class internally). The code fragment below shows how the client saves the arguments and synchronizes access to a block of code.

C#
Copy Code

private void NotifyCallback(NotifyCommand command, object data)
{
   // synchronize access to this block of code
   lock(this)
   {
      // save arguments to class fields
      notifyCommand = command;
      notifyData = data;

      // execute the method on the GUI's thread, this method
      // uses the notifyCommand and notifyData fields
      Invoke(processCommand);
   }
}


Source : MSDN
Thiruvasakamani Karnan