Nik Bo
Nik Bo

Reputation: 1410

Cross Thread event receiver

For my project I'm using a combination of C# UI and C++ DLL as "worker". My Application uses the Irrlicht Engine for rendering. A panel in my C# window is used as Container for the Scene.

Currently I'm implementing an event receiver for mouse interactions. My Problem, the C++ Code don't receive events.

I worked out the core problem: It's necessary, that I'm using a rende loop, that the C++ Code have the chance to catch the event. For this loop I must use a Thread, otherwise my C# window gets freezed. Now the issue, the events don't gets send to my receiver, because the events are from another thread.

Irrlicht System Messages Handler

if (msg.hwnd == HWnd)  //My issue msg.hwnd = Main Thread HWnd = Render Thread
{
     WndProc(HWnd, msg.message, msg.wParam, msg.lParam);  //On this way my event receiver would get the event.
}
else
{
    TranslateMessage(&msg);
    DispatchMessage(&msg);
}

Now I must found a solution, how I can contiously render and forwarding events from main Thread to render Thread.

My current work around is the dirty way:

C# Code

while (!RenderStop) //bool to stop this loop
{
    MyDll.RenderScene();   // Calculate and redraw changes
    Application.DoEvents();
}

It's no good way but with this I'm getting an fake parallelism and the events reachs my DLL.

Ps. All events are just simple MouseMove or Click events.

Upvotes: 2

Views: 172

Answers (1)

Michał Komorowski
Michał Komorowski

Reputation: 6238

I would try to do as follows:

  1. Define additional method in your worker that would be responsible for handling events, for example: HandleMouseEvent.
  2. Run worker in the separate thread.
  3. Subscribe mouse events in the main UI thread.
  4. When a new event is raised call MyDll.HandleMouseEvent.

I don't know what RenderScene actually does. However, please note that HandleMouseEvent and RenderScene methods would be called in different threads. It means that you may need to synchronize access to data structures used by your worker (MyDll).

Another solution might be to use some .NET wrapper for Irrlicht Engine instead of writing it on your own. For example, I've found Irrlicht Lime. However, I have to admit I didn't use it.

Upvotes: 1

Related Questions