Subj : Re: Problems with event raised from 2nd thread (C#) To : comp.programming.threads From : Joseph Seigh Date : Sat Jan 22 2005 09:50 am On 22 Jan 2005 04:47:13 -0800, wrote: > I have a standate WinForms application (C#) which needs to read and > process data from a serial port. > > My UI runs on the standard thread but I start a new thread to read from > the serial port and process the data received. When specific data is > found by the serial-port-reading thread, an event is raised which is > consumed by the main UI thread(?). This results in data being taken > from the serial port class and the UI being updated. > > I know it is a BAD THING to allow the UI to be updated from 2ndary > threads (but I'm not too clear on the reasons). A lot of the UI is probably written assuming that it is only updated by the GUI event handling thread and its resources are not shared. To use those interfaces you have to create and enqueue your own GUI event using whatever api C# uses for that. There may be interfaces that are invocable by any threads but you'll have to check the documentation. > > I'm asking this question because the application is hanging so clearly > I've broken some rules and caused a deadlock? Probably by not using a lock hierarchy to avoid deadlock or by calling an interface that was meant to be called asynchronously to avoid deadlock from recursion. OO method invocations are really callbacks and if you're arbitrarily locking objects for no good reason at all and not paying attention to what's calling what, you're going to get into trouble. First learn that locking is for. Just because an object has a builtin mutex doesn't mean you have to use it or that using it makes things safe somehow. C# borrowed object locking from Java and it's one of the top 10 worst language design decisions ever made (Java has about 20 of the top 10 worst). Once you've figured out what has to be protected by a lock, *then* decide where the lock should be and where it gets invoked. And learn how to create or determine a lock hierarchy and adhere to it. > > Is the UI update done by the function consuming the event done on the > 2ndary thread or the main UI thread? Any suggestions on how to rework > this? The functions (methods) are executed on the thread that invoked them. Obviously, GUI functions that are only meant to be invoked by the GUI event handling thread should not be invoked from other threads. > > I prefer to have the serial-port raise an event rather than a timer on > the UI as there will be several screens that may want to process this > data... > You should be able to enqueue a GUI type event or invoke the GUI "refresh" (or whatever they call it) that does an asynchronous call the the GUI thread. I can't give you specifics on C# since I don't use it and my Java experience is pretty out of date by now. -- Joe Seigh .