我必须使用外部API,无论出于什么原因,只要它在WPF应用程序的UI线程中初始化并运行,它就能工作。如果我启动一个不使用UI同步上下文的任务/线程,即使在WPF测试应用程序中,API也不起作用。
我需要让它在控制台应用程序,Windows服务,类库中运行......但不能在WPF应用程序中运行。
答案 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
引用。