问题描述:

I'm writing Windows / Windows Phone 8.1 application that has needs to invoke a native C++/CX class in the background.

At the moment I have a code like this (inside an async method(

var list = await Task.Run(()=> {

var parser = new NativeParser();

return parser.process("someData"); //here I get the exception

});

on the call of .process() I get an exception saying WinRT information: The application called an interface that was marshalled for a different thread.

The problem is that I'd like to what exactly is the problem - isn't the native class also created on background (inside Task.Run?)

Edit:

I tried to do the same inside a ThreadPool call - and the same thing happens. Is there some weird C# to C++/CX interop thing that I'm not aware of?

 IAsyncAction asyncAction = ThreadPool.RunAsync((workItem) =>

{

var parser = new NativeParser();

return parser.process("someData");

});

asyncAction.Completed = new AsyncActionCompletedHandler(

(IAsyncAction asyncInfo, AsyncStatus asyncStatus) =>

{

Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>

{

// update UI

}

});

网友答案:

Found the culprit - while stepping through the code I discovered that it crashed on the line where my C++/CX code was creating a ref new Foo();, where Foo was derived from Windows::UI::Xaml::DependencyObject (seemed like a nice base class at the moment as the only possible public unsealed types are those found under the Windows::UI::Xaml namespace, and users are not able to create their own public unsealed types).

Apparently you can only create and access XAML elements that inherit from DependencyObject from the XAML UI thread of an app, so I have to refactor the code to avoid inheriting from that one.

相关阅读:
Top