I am creating a non-visual component in .Net 2.0. This component uses an asynchronous socket (BeginReceive, EndReceive, etc.). Asynchronous callbacks are called in the context of the workflow created by the runtime. The component user does not need to worry about multithreading (this is the main goal that I want)
A component user can create my non-visual component in any thread (the user interface thread is just a common thread for simple applications. More serious applications can create a component in an arbitrary workflow). The component fires events such as "SessionConnected" or "DataAvailable".
Problem: Due to asynchronous callbacks and related events, the event handler runs in the context of the workflow. I want to use an intermediate layer that enhances the event handler to execute in the context of the thread that created the component in the first place.
Sample code (devoid of exception handling, etc.)
/// <summary> /// Occurs when the connection is ended /// </summary> /// <param name="ar">The IAsyncResult to read the information from</param> private void EndConnect(IAsyncResult ar) { // pass connection status with event this.Socket.EndConnect(ar); this.Stream = new NetworkStream(this.Socket); // -- FIRE CONNECTED EVENT HERE -- // Setup Receive Callback this.Receive(); } /// <summary> /// Occurs when data receive is done; when 0 bytes were received we can assume the connection was closed so we should disconnect /// </summary> /// <param name="ar">The IAsyncResult that was used by BeginRead</param> private void EndReceive(IAsyncResult ar) { int nBytes; nBytes = this.Stream.EndRead(ar); if (nBytes > 0) { // -- FIRE RECEIVED DATA EVENT HERE -- // Setup next Receive Callback if (this.Connected) this.Receive(); } else { this.Disconnect(); } }
Due to the nature of Async sockets, all applications using my component are dotted with "If (this.InvokeRequired) {...", and all I want is that the user can use my component without problems like a drop sort.
So, how could I raise events without requiring the user to check InvokeRequired (or, in other words, how can I force events raised in the same thread as the thread that raised the event in the first place)?
I read stuff about AsyncOperation, BackgroundWorkers, SynchronizingObjects, AsyncCallbacks and tons of other things, but it all makes my head spin.
I really came up with this, of course, a clumsy βsolutionβ, but it doesn't seem to work in some situations (when my component is called from a WinForms project through a static class, for example)
/// <summary> /// Raises an event, ensuring BeginInvoke is called for controls that require invoke /// </summary> /// <param name="eventDelegate"></param> /// <param name="args"></param> /// <remarks>http://www.eggheadcafe.com/articles/20060727.asp</remarks> protected void RaiseEvent(Delegate eventDelegate, object[] args) { if (eventDelegate != null) { try { Control ed = eventDelegate.Target as Control; if ((ed != null) && (ed.InvokeRequired)) ed.Invoke(eventDelegate, args); else eventDelegate.DynamicInvoke(args); } catch (Exception ex) { Console.WriteLine(ex.GetType()); Console.WriteLine(ex.Message); //Swallow } } }
Any help would be greatly appreciated. Thanks in advance!
EDIT: According to this topic , the best option would be to use SyncrhonizationContext.Post, but I don't see how to apply it to my situation.