Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.9k views
in Technique[技术] by (71.8m points)

multithreading - C# UWP The application called an interface that was marshalled for a different thread

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 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))

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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).

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

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.

You can generally find your dispatcher from your Window via Window.Dispatcher.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...