c# - Thread Apartment State -
all,
i have been using threads while in c# still bit confused thread's apartment state means. know winforms must use sta apartment state (as opposed mta) still not clear apartment states about.
com had lofty goals. 1 of them threading programming detail hard right , should managed support libraries. unlike .net entirely use classes not thread-safe in thread-safe manner.
this works through registry, com coclass publishes threadingmodel registry key says kind of threading supports. far of them use "apartment", unclear way "i don't support multi-threading". signal com make sure of methods called in thread-safe manner. if program calls method worker thread com takes care of marshaling call worker thread created instance. automatically ensuring server used in thread-safe manner. not unlike way control.invoke , dispatcher.invoke works, automatically.
this wonderful magic of course, program have co-operate bit. com cannot marshal calls without help. when program creates thread, must call coinitialize() tell com infrastructure want participate in com calls. @ time, have tell kind of thread created. there two, distinguished 'apartment' type. there sta (single threaded apartment) , mta (multiple). sta thread hospitable home com components don't support threading. mta thread not.
there's price tag attached kind of apartment though. when create sta have follow sta rules. bit draconic:
- you must pump windows message loop
- you can never block thread
the message loop mechanism com marshals calls 1 thread another. never-block rule required prevent deadlock. while draconic, way ui thread of program works. not coincidence.
there's price tag attached creating apartment threaded com object on mta thread. such thread not home, doesn't follow sta rules. com cannot helpful , method calls marshaled. com steps in , creates own sta thread give object hospitable home. nice, not cheap since burns thread , every method call marshaled, adds lot of overhead every single call.
com threading support quite nice, takes care of 98% of time without having special. 2% can give enormous migraine, there's little can whack it. scales poorly, biggest reason .net doesn't have similar.
while com might appear dead, apartments still big deal in windows programming. .net framework has explicit support them. calling thread.join() or monitor.enter() on sta thread example, explicitly verboten com, makes clr pump message loop. other artifacts [stathread] attribute see on main() method of gui app , thread.setapartmentstate(), ways clr call coinitialize() correct way. gui features clipboard, drag , drop , shell dialogs (like openfiledialog) explicitly require sta work. thread creates windows should sta thread.
Comments
Post a Comment