Search code examples
c#wpfsilverlightwindows-phonemvvm-light

MvvmLightToolkit: Is the DispatcherHelper.Initialize() method's execution needed?


The Mvvm Light Toolkit include the DispatcherHelper that is a very useful tool. It allows to synchronize the main UI Thread from a background thread in a very simple way. For instance DispatcherHelper.CheckBeginInvokeOnUI():

//In any moment before...
DispatcherHelper.Initialize();

ThreadPool.QueueUserWorkItem(
    o => 
    {
        //Do something

        DispatcherHelper.CheckBeginInvokeOnUI(()=>StatusTextBlock.Text = "Done");
    }
);

Before using the DispatcherHelper I usually use the MainThread's SynchronizationContext for submitting any change from a non main thread to the view.

My question is: why is it necessary the DispatcherHelper.Initialize method execution before using the class? Can it be called on the static constructor for the first time? For instance:

public class DispatcherHelper
{
    private static void Initialize()
    {
         //...
    }
    static DispatcherHelper(){
        Initialize();
    }
    //...
}

I think in this way it is not needed


Solution

  • After making a research, I think I found a good reason:

    This reason could be that DispatcherHelper.Initialize(); method should be executed in the main thread, and if it is done automatically using the static constructor, there exists a possibility that the static constructor executes on another background thread.