【发布时间】:2014-02-25 16:00:37
【问题描述】:
因此,我们正在为 Windows 应用商店开发新应用,我们在应用的 C++/CX 部分使用 DirectX,在其他应用中使用 C#。由于我们需要某种通信,我们在共享库 (C#) 和在项目的 C# 端实现它的类中创建了接口。然后我们将该类的实例传递给 C++。当 C++ 需要与 c# 通信时,它从共享接口调用方法,c# 执行类中实现的内容。
当 C++ 从另一个线程调用方法而不是将对象传递给它时,就会出现问题。错误:
The application called an interface that was marshalled for a different thread.
它是这样工作的:
C# instance of shared interface (some class)
C# -> C++ \/ passed in parameter of public C++ method
C++ saves to variable
C++ creates new thread
C++ calls instance->SayHello();
C# exception
共享接口:(C#)
public interface IUserMessageService
{
void WriteMessage(string message, MessageTypes type);
}
实现:(C#)
public sealed class UserMessageService : IUserMessageService
{ ... }
赋值方法(C++)
void AssignUserMessageService(...::IUserMessageService ^service) { m_service = service; }
然后我从 UI 线程调用 AssignUserMessageService 并使用 UserMessageService 的实例。当我在另一个线程中调用 WriteMessage 时尝试访问 C++ 传递的数据时发生错误。
还有其他方法可以传递实例或调用方法吗?
【问题讨论】:
-
@Matt 确实对我有用。错误是我使用的
CoreApplication.MainWindow.CoreWindow.Dispatcher看起来不是 UI 线程调度程序...
标签: c# multithreading windows-runtime marshalling c++-cx