I am trying to create a second message loop for asynchronously processing / filtering low-level messages in C #. It works by creating a hidden form, revealing its Handle property for connection and launching the second message loop in a separate thread. At the moment, I am satisfied with the results, but I canβt normally exit the second cycle. The only workaround was to set the IsBackground property to true, so the second thread would simply terminate (without processing all pending messages) when exiting the main application.
The question arises: how to correctly exit the message loop so that the second Application.Run () application returns? I tried different approaches to creating a separate ApplicationContext and managing various events (Application.ApplicationExit, Application.ThreadExit, ApplicationContext.ThreadExit), but they all could not cope with the conditions of the race. I can not debug.
Any hint? Thanks
This is the code:
public class MessagePump { public delegate void HandleHelper(IntPtr handle); public MessagePump(HandleHelper handleHelper, Filter filter) { Thread thread = new Thread(delegate() { ApplicationContext applicationContext = new ApplicationContext(); Form form = new Form(); handleHelper(form.Handle); Application.AddMessageFilter(new MessageFilter(filter)); Application.Run(applicationContext); }); thread.SetApartmentState(ApartmentState.STA); thread.IsBackground = true;
I use it in the main form constructor as follows:
_Completion = new ManualResetEvent(false); MessagePump pump = new MessagePump( delegate(IntPtr handle) { // Sample code, I did this form twain drivers low level wrapping _Scanner = new TwainSM(handle); _Scanner.LoadDs("EPSON Perfection V30/V300"); }, delegate(ref Message m) { // Asyncrhronous processing of the messages // When the correct message is found --> _Completion.Set(); }
EDIT : complete solution in my answer.
source share