I have a thread which extracts data from a socket’s web request. It updates the UI of the window who made the call through an event.
The thread and socket are instantiated when the app opens and are kept around as a global property. The socket runs the thread when a response is received.
Before making a request, the window sets a property on the socket for the state of the socket and a property for the calling window.
Now this is the part where I think is bad design. The calling window type is a subclass of window. It has one method and many event definitions which handle all the different web responses. When the thread is ready to update the UI, it calls that one method. That method looks at the current state and raises the appropriate event on the window.
No window needs to handle all responses and two or more windows need to be able handle the same response, but using their own implementation.
Is there a better way to do this using delegates or some other design?
Did you consider an interface? Making the thread class an interface sender class and the window a receiver class would make it possible to just send a notification to the interface receiver class and have different, individual responses because of different “Notification Received” (or whatever you like to call them) method implementations.
Interface is my first thought too.
Your interface could define a method for each response type. The window would only need to implement the ones it needs to know about. (the others can be left empty).
The sender could loop through the open windows and test for window(x) isa myReceiverInterface, then call the function, like myReceiverInterface(window(x)).theFunction
I agree that an interface is the right way to go. Be aware, though, that any way to go, even though the method is part of the window definition, if it is called from the thread, it runs in the context of the thread and therefore can’t update the UI. I’m guessing you’ll want to use a Task or Timer to call the method, rather than call it directly from the thread.