Multiple dispatcher problem

I have the following problem, WPF multithreaded application, implementation of a model view view. Representatives and views that belong to each other are created by the factory on a separate thread and must receive a separate dispatcher.

Public Function CreatePresenter(Of T As {New, Class})(ByVal p_eCreationOptions As eViewCreationOptions) As T Implements IPresenterFactory.CreatePresenter

    Select Case p_eCreationOptions
        Case eViewCreationOptions.CreateInCallingThread
            CreatePresenter(Of T)()
        Case eViewCreationOptions.CreateInNewThread
            Dim oThread As New Thread(New ThreadStart(AddressOf CreatePresenter(Of T)))
            oThread.SetApartmentState(System.Threading.ApartmentState.STA)
            oThread.Start()
            oThread.Join()
        Case Else
            Throw New InvalidOperationException("Need to specify creation options.")
    End Select

    Return CType(m_oCreatedPresenter, T)

End Function

Private Sub CreatePresenter(Of T As {New, Class})()
    m_oCreatedPresenter = Activator.CreateInstance(Of T)()
End Sub

      

The problem is that now the creator is created on a different thread and the thread becomes dormant after creation, but the dispatcher is not working there yet. Now if I come from the main UI thread where the application lives and makes a call to my presenter, I create a view, show it, and now only I can call Dispatcher.Run ().

Public Overloads Sub Show()
    Console.WriteLine ("Show Caller ThreadID = " & Thread.CurrentThread.ManagedThreadId)
    MyBase.Show()
    System.Windows.Threading.Dispatcher.Run()
End Sub

      

But what I want to do is when the method on the presenter is called from a thread other than where the presenter lives, call the method again on the presenter's thread where it has its own Dispatcher, t need to deal with the dispatcher when making calls between my presenter and presentation. Is this even possible, my design is flawed, or is there a better way to achieve what I want?

+1


source to share


1 answer


The problem is that the dispatcher does not start when the DispatcherObject is not instantiated on a new thread, but if you instantiate a mock object and then call a method on your master, the dispatcher will work as expected. for example

 private void ThreadStartingPoint()  
 {  
     var dummyDispatcherObject = new Style();  
     Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(CreatePresenterInternal));  
     Dispatcher.Run();  
}  

      



A complete solution to this question can be found on my blog .

+2


source







All Articles