Recommended

  • Silverlight 4 Podcast Pack with Tim Heuer
  • Building Modular Silverlight Applications
  • Prism -  10 Things to Know
  • Securing Silverlight Application and WCF Service using ASP.Net Authentication Techniques
  • Model– View – ViewModel in Silverlight
Skip Navigation LinksHome / Tips / View Tip

Tip: How to invoke method in the UI thread?

+ Add to SilverlightShow Favorites
2 comments   /   posted by Denislav Savkov on Aug 29, 2008
(0 votes)
Categories: Controls and UI

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!
Share


Comments

Comments RSS RSS
  • 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 );
    
       }
    }
    

     

  • 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

 
 

   
  
  
   
Please add 1 and 7 and type the answer here: