JD.
JD.

Reputation: 15531

How does dispatcher work the a thread?

We have a silverlight application which uses a dispatcher and I would appreciate any help explaining what the following codes does? (unfortunately the developer who wrote the code has left).

So what we have is the following:

public class ABC
{
    private Dispatcher dispatcher;
    private Thread threadRunner;

    public void ABC()
    {
       threadRunner= new Thread(ThreadRunnerMethod)
                         {
                           IsBackground = true, 
                           ApartmentState = ApartmentState.STA
                         };
       threadRunner.Start();
    }

    private static void ThreadRunnerMethod()
    {
       Dispatcher.Run();
    }


    public void MainMethod()
    {
       dispatcher = Dispatcher.FromThread(threadRunner);
       dispatcher.Invoke(new Action(() => 
                                     // "DO SOME WORK WITH A COM OBJECT"
                                      ));

    }
}

I have some basic experience with threading but I have no idea how this all works?

JD

Upvotes: 3

Views: 3387

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1499770

It's the equivalent of Control.Invoke in Windows Forms, basically - it's just been separated into its own object.

As I understand it, Dispatcher.Run will basically start an event loop, and you can marshall calls into that event loop using Dispatcher.Invoke. Dispatcher.FromThread finds the Dispatcher object which is responsible for a given thread - so in this case, it finds the event loop running in the new thread.

So in your code, the delegate created with the lambda expression will execute in the newly created thread.

Upvotes: 3

Related Questions