(X) Hide this
    • Login
    • Join
      • Generate New Image
        By clicking 'Register' you accept the terms of use .
        Login with Facebook

Tip: How to invoke method in the UI thread?

(0 votes)
Denislav Savkov
>
Denislav Savkov
Joined Feb 11, 2008
Articles:   14
Comments:   6
More Articles
2 comments   /   posted on Aug 29, 2008
Categories:   General

If you have used multiple threads or just timers in your applications, you probably know that if you have to update any user interface, control you should not do it from any other thread but from the one that the control was created from. That is why if your application uses multiple threads, you always have to be aware of what thread you are in.
In Silverlight invoking a piece of code in the user interface thread can be achieved by using the BeginInvoke method of the System.Windows.Threading.Dispatcher class. However you cannot create an instance of the Dispatcher class but you can use the one each object that derives from System.Windows.DependencyObject exposes through its Dispatcher property.
Check out the code snippet bellow:

C#

// Method executed in some other non UI thread!
private void OtherThreadMethod()
{
    //Invoke the method that should change the control in the UI thread
    this.Dispatcher.BeginInvoke( UIThreadMethod );
}
 
private void UIThreadMethod()
{
    //Perform the change of the control
    this.Cursor = Cursors.Wait;
}
That's it!

Subscribe

Comments

  • -_-

    RE: How to invoke method in the UI thread?


    posted by aquaseal on Aug 29, 2008 14:17

    Also, a hidden method (hidden from intellisense) is CheckAccess() which is very useful to see if the thread is on the render thread and if not invoke that same method again. Here's a quick example:

    private void OtherThreadMethod()
    
    {
    
       if(!this.Dispatcher.CheckAccess())
    
       {
    
          this.Dispatcher.BeginInvoke( OtherThreadMethod );
    
       }
    }
    

     

  • iiordanov

    RE: How to invoke method in the UI thread?


    posted by iiordanov on Sep 01, 2008 04:27

    10x aquaseal!

    This is also very useful method!

Add Comment

Login to comment:
  *      *       
Login with Facebook