2010-11-17 30 views

Respuesta

3

se parece a todas parte con hilo en mvvmlight es esta clase:

public static class DispatcherHelper 
{ 

    public static Dispatcher UIDispatcher 
    { 
     get; 
     private set; 
    } 

    /// <summary> 
    /// Executes an action on the UI thread. If this method is called 
    /// from the UI thread, the action is executed immendiately. If the 
    /// method is called from another thread, the action will be enqueued 
    /// on the UI thread's dispatcher and executed asynchronously. 
    /// <para>For additional operations on the UI thread, you can get a 
    /// reference to the UI thread's dispatcher thanks to the property 
    /// <see cref="UIDispatcher" /></para>. 
    /// </summary> 
    /// <param name="action">The action that will be executed on the UI 
    /// thread.</param> 
    public static void CheckBeginInvokeOnUI(Action action) 
    { 
     if (UIDispatcher.CheckAccess()) 
     { 
      action(); 
     } 
     else 
     { 
      UIDispatcher.BeginInvoke(action); 
     } 
    } 

    /// <summary> 
    /// This method should be called once on the UI thread to ensure that 
    /// the <see cref="UIDispatcher" /> property is initialized. 
    /// <para>In a Silverlight application, call this method in the 
    /// Application_Startup event handler, after the MainPage is constructed.</para> 
    /// <para>In WPF, call this method on the static App() constructor.</para> 
    /// </summary> 
    public static void Initialize() 
    { 
     if (UIDispatcher != null) 
     { 
      return; 
     } 

     // for silverlight 
     UIDispatcher = Deployment.Current.Dispatcher; 

     // wpf 
     //IDispatcher = Dispatcher.CurrentDispatcher; 

    } 
} 

}

y eso es todo. Utilice DispatcherHelper.Initialize() de acuerdo a comentar en la App constructor estático (WPF) o controlador de eventos Application_Startup (Silverlight) - y entonces u puede utilizar DispatcherHelper.CheckBeginInvokeOnUI (acción Acción)

Saludos

+0

Gracias agenda de discusión. ¿Qué tal si se compara con el enhebrado .net normal y se puede usar en los viewmodels? –

+0

1. primero u inicializa la clase DispatcherHelper invocando el método Initialize() - y debes hacerlo en el hilo ui para que pueda recordar/establecer su referencia privada al despachador – agend

+0

2. después de eso puedes usar DispatcherHelper.CheckBeginInvokeOnUI (Acción) - desde cualquier lugar que desee - view, model, viewmodel - siempre usará el subproceso ui para invocar su acción 3. acerca de la comparación de subprocesamiento .NET normal - normalmente tendría que hacer estas cosas por su cuenta: mantener la referencia a la interfaz de usuario despachador, compruebe que está en el hilo de ui, y finalmente llame a dispatcher.BeginInvoke (acción) - con esta clase es más fácil – agend

Cuestiones relacionadas