C# threads - Posting messages between threads
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#
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.
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.
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.
精彩评论