Floating FB sharing byReview Results

Floating FB sharing byReview Results

  • WPF Tutorial

    • # Read in Your Language


    Dependency Property

    Tutorial Home | Dependency Properties | Attached Properties| Routed Events | Dispatcher in WPF | DispatcherUnhandledException

    Dispatcher in WPF

    Dispatcher:


    A Control created in one thread cannot be accesses from other thread in .net 2.0, this can be achieved using invoke method.
    We have similar and even better concept in WPF.ie Dispatcher.

    Namespace : System.Windows.Threading.Dispatcher.

    Every control in WPF inherits dispatch object. This is the object that allows handling UI dispatcher. You can't directly update controls from outside threads for dispatcher objects. if you try accesses it you'll get a runtime exception.

    
        Button btn1 = new Button();
        btn1.Content = "Test";
    
        System.Threading.Thread thread = new 
        System.Threading.Thread(
          new System.Threading.ThreadStart(
            delegate()
            {
                btn1.Content = "From Thread";
            }
        ));
        thread.Start();
      
    The code above creates a Button, then starts a thread which tries to change the content of button.

    This gives the following exception:
    The calling thread cannot access this object because a different thread owns it.

    The Dispatcher gives the user the ability to Invoke onto its thread using Invoke or BeginInvoke,BeginInvoke is asynchronous. Invoking here is similar to that of framework 2.0. Dispatcher will set the priority for the items for the specified thread.
    Dispatcher created on a thread is the only Dispatcher that can be associated with that thread.
    Here Dispatcher will run and update the Button content without throwing any exception.

    
     Button  btn1  = new Button();
     btn1.Content = "Test";
    
      System.Threading.Thread thread = new 
      System.Threading.Thread(
        new System.Threading.ThreadStart(
          delegate()
          {
           btn1 .Dispatcher.Invoke(
           System.Windows.Threading.DispatcherPriority.Normal,
              new Action(
                delegate()
                {
                 btn1.Content = "From Thread";
                }
            ));
          }
      ));
      thread.Start();
     
    The amount of time the invoke takes can be controlled by setting timespan.
    
    btn1.Dispatcher.Invoke(
    System.Windows.Threading.DispatcherPriority.SystemIdle,
              TimeSpan.FromSeconds(5),
              new Action(
                delegate()
                {
                    btn1.Content = "From Thread";
                }
            ));
     


    << Previous >> | << Next >>