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

查看:290
本文介绍了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 = -2147417842 Message =该应用程序调用了一个已编组用于另一个线程的接口. (来自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.

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天全站免登陆