我可以在控制台应用程序或类库中模拟或以某种方式创建WPF UI线程吗?

时间:2015-12-09 05:45:10

标签: c# wpf api task ui-thread

我必须使用外部API,无论出于什么原因,只要它在WPF应用程序的UI线程中初始化并运行,它就能工作。如果我启动一个不使用UI同步上下文的任务/线程,即使在WPF测试应用程序中,API也不起作用。

我需要让它在控制台应用程序,Windows服务,类库中运行......但不能在WPF应用程序中运行。

1 个答案:

答案 0 :(得分:2)

这适用于控制台应用程序

我不确定您的案例是否需要Dispatcher,或者代码只需要STA公寓状态。

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();
    }
}

您只需要为WindowsBase.dll添加Dispatcher引用。