C# UWP 应用程序调用了一个为不同线程编组的接口 [英] C# UWP The application called an interface that was marshalled for a different thread

查看:17
本文介绍了C# UWP 应用程序调用了一个为不同线程编组的接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 C# UWP 应用程序,其中包含一个我想每 5 秒调用一次的函数.当从按钮调用该函数时,该函数运行良好,并且 Timer 每 5 秒写入调试控制台一次……当我从 Timer 调用该函数时,一切都崩溃了.我明白了:

I have a C# UWP app that contains a function I want to call every 5 seconds. The function runs fine when called from a button, and the Timer write to the debug console fine every 5 seconds....When I call the function from the Timer, all heck breaks loose. I get this:

System.Exception 未被用户代码处理HResult=-2147417842Message=应用程序调用了一个为不同线程编组的接口.(来自 HRESULT 的异常:0x8001010E (RPC_E_WRONG_THREAD))

System.Exception was unhandled by user code HResult=-2147417842 Message=The application called an interface that was marshalled for a different thread. (Exception from HRESULT: 0x8001010E (RPC_E_WRONG_THREAD))

推荐答案

我假设您的函数涉及应用程序的 UI.任何接触 UI 的东西都需要在 UI 的调度程序线程上运行(大多数应用程序只有一个,直到您进入多个窗口应用程序).

I assume your function touches the app's UI. Anything which touches the UI needs to run on the UI's dispatcher thread (most apps will have only one until you get into multiple window apps).

您可以使用 Windows.UI.Xaml.DispatcherTimer 在调度程序线程上运行你的计时器.

You can use a Windows.UI.Xaml.DispatcherTimer to run your timer on the dispatcher thread.

如果您需要在工作线程上运行代码,然后在调度程序线程上触摸 UI,您可以调用 Dispatcher.RunAsync 将回调编组回调度程序线程.

If you need to run code on a worker thread and then touch UI on the dispatcher thread you can call Dispatcher.RunAsync to marshal a call back onto the dispatcher thread.

您通常可以通过 Window.Dispatcher.

var ignored = Window.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
   // Do something on the dispatcher thread
});

这篇关于C# UWP 应用程序调用了一个为不同线程编组的接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆