3

I have to use an external API that for whatever reason only works as long as it is initialized and run on a WPF app's UI thread. If I spin up a task/thread that does not use the UI Synchonization Context even within a WPF test app the API does not work.

I need to make it work within a Console App, Windows Service, class library...but not WPF application.

Matt
  • 7,004
  • 11
  • 71
  • 117

1 Answers1

4

This works for me in console application

I'm not sure whether Dispatcher is needed for your case or the code simply requires STA apartment state.

class Program
{
    static void Main(string[] args)
    {
        var thread = new Thread(() =>
        {
            Dispatcher.CurrentDispatcher.BeginInvoke(new Action(() =>
            {
                Console.WriteLine("Hello world from Dispatcher");
            }));

            Dispatcher.Run();
        });

        thread.SetApartmentState(ApartmentState.STA);
        thread.Start();
        thread.Join();
    }
}

You just need to add WindowsBase.dll reference for Dispatcher.

ghord
  • 13,260
  • 6
  • 44
  • 69