I have a sort of plug-in model in which various complex user controls are stored in DLLs and loaded and instantiated at run time using
Activator.CreateInstanceFrom(dllpath, classname).
Since I'm loading quite a few of these I wanted to do it in the background, keeping my UI responsive, by creating a new thread to do the loading. The controls are then parented to the main form and displayed when needed.
This seems to work fine - until I try to set any property on any nested control on one of these user controls, e.g. in the event handler of a button, which throws a cross threading exception. I do realize I could avoid this by checking InvokeRequired every time I access a property, but I'd rather not have to worry about that when writing the code for the user controls (especially since there are others writing these bits of code too who might not always remember).
So my question is, is there any safe way to do what I'm attempting, or how should I best go about loading these controls in the background? Or is it basically impossible and do I have to stick to the main thread for creating controls?
I hope that the information I've provided is enough to make my situation clear; if not I'd be glad to elaborate and provide code samples.
See Question&Answers more detail:os