views:

76

answers:

3

Hi All,

I am working on a project which involves reusing as well as migrating some of the existing MFC code to C#.

The current code in MFC, creates some threads and uses ::PostthreadeMessage() and ON_THREAD_MESSAGE(msg,func) for inter thread asynchronous communication through messages.

::PostthreadeMessage() -> sends a message to a particular thread id. ON_THREAD_MESSAGE(msg,func) -> calls the function(func) when a message(msg) is received.

Since i am not much aware of the threading interfaces in C#, i tried to search for similar API's in C#, but was not able to find any.

It would be great, if somebody can help me in finding the appropriate functions for this purpose in C#

Thanks, Harsha

+1  A: 

Here's the advice from C# MVP Nicholas Paldino:

If you are posting to the thread, and not to a specific window, then you will have to have something that implements the IMessageFilter interface, and then pass that implementation to the static AddMessageFilter method on the Application class, so it can handle the message that comes in on the thread.

From the other thread, you will have to use the PostThreadMessage API method through the P/Invoke layer.

Mitch Wheat
There is a risk to this approach. PostThreadMessage posts a message using the threadId, but the relationship between the threadId and a managed thread is not fixed. From MSDN "An operating-system ThreadId has no fixed relationship to a managed thread, because an unmanaged host can control the relationship between managed and unmanaged threads."http://msdn.microsoft.com/en-us/library/74169f59.aspx
Chris Taylor
Thanks to Chris and Mitch!!!Just needed couple of more clarifications on your suggestions.You mentioned about the PostThreadMessage API. Is it the one from user32 dll, which i can dllimport and use it?If so, then where exactly should i implement IMessageFilter interface and why?Without implementing it, can't i import the getmessage and postthreadmessage from user32 dll and use it?Thanks!
Harsha
A: 

I would advice you against doing a direct port for this (inter thread communication) part of the application. May be you can check if you can use delegates and events. A delegate could be registered at startup and these delegates (callbacks) could be called instead of the user message.

Sudesh Sawant
A: 

If both of your threads are in C# and you are on .NET 4 I would just use a ConcurrentQueue<T> and queue up messages from one thread and then consume them on the other.

Hightechrider
Thanks for the info!! I am on .NET3.5. My threads will be created in C# and needs to communicate to each other. Also each thread will use some MFC dll, and from that MFC code, i want to communicate to the other thread in C# using thread id.Hope it gives you some idea!!!
Harsha