Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/wpf/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ionic-framework/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Wpf 如何切换已启动线程的ApartmentState_Wpf_Multithreading_<img Src="//i.stack.imgur.com/WM7S8.png" Height="16" Width="18" Alt="" Class="sponsor Tag Img">servicestack_Server Sent Events - Fatal编程技术网 servicestack,server-sent-events,Wpf,Multithreading,servicestack,Server Sent Events" /> servicestack,server-sent-events,Wpf,Multithreading,servicestack,Server Sent Events" />

Wpf 如何切换已启动线程的ApartmentState

Wpf 如何切换已启动线程的ApartmentState,wpf,multithreading,servicestack,server-sent-events,Wpf,Multithreading,servicestack,Server Sent Events,我在WPF中使用ServiceStack的SSE特性作为聊天机制。我已经注册了OnMessage方法,在从服务器接收到合适的消息后,我正在其中创建一个聊天消息视图。我得到了“调用线程必须是STA,因为许多UI组件都需要这个”异常,这立即让我假设调用线程不是我的主线程,快速调试表明了这一点。SSE创建了自己的线程,而且线程ApartmentState没有设置为STA。我可以做些什么来缓解这个问题 在这个实例中,使用Application.Current.Dispatcher.Invoke是否是创建

我在WPF中使用ServiceStack的SSE特性作为聊天机制。我已经注册了OnMessage方法,在从服务器接收到合适的消息后,我正在其中创建一个聊天消息视图。我得到了“调用线程必须是STA,因为许多UI组件都需要这个”异常,这立即让我假设调用线程不是我的主线程,快速调试表明了这一点。SSE创建了自己的线程,而且线程ApartmentState没有设置为STA。我可以做些什么来缓解这个问题

在这个实例中,使用
Application.Current.Dispatcher.Invoke
是否是创建我的视图的好方法


我还考虑在每次调用我的
OnMessage
registered方法时创建一个新的STA线程,但这意味着在每条聊天消息上创建一个新线程。

切换是不可能的。STA是WPF借用的术语。这实际上意味着不能从工作线程更新UI组件,WPF不是线程安全的。严格将计算工作与UI更新分开,支持BackgroundWorker或TaskScheduler.FromCurrentSynchronizationContext()或async/Wait进行分离。如果出于某种原因必须使用Dispatcher.Invoke(),请始终选择BeginInvoke()。