views:

251

answers:

1

Hi,

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

+1  A: 

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.

Jon Skeet
Hi Jon, Thanks for the reply. For Control.invoke() if I am correct, we are queueing tasks for the main thread to do?. Here, the tasks are done in the new thread? Also, if another task is kicked off, would it simply add it to the queue for the new thread to do and not block the calling thread?Thanks
JD
In both cases, we're queuing tasks for "a thread which is running an event loop" to do. For WinForms, that's the UI thread - which doesn't have to be the one that your app started on, necessarily. If you call Invoke it *will* block the calling thread; BeginInvoke doesn't.
Jon Skeet
Thank you so much. It is now clear what is going on.I ordered your book yesterday, cant wait to read it.JD.
JD
@JD: Cool - hope you enjoy it!
Jon Skeet