.netcomasynchronousbegininvokeapartment-state

can I modify the nature of the thread that will BeginInvoke my delegate?


I am implementing an interface that has a BeginSomething() and EndSomething() pair, and my implementation is in a method Execute()

So I create an Action action = Execute, and call action.BeginInvoke in BeginSomething, and action.EndInvoke in EndSomething. However my Execute method has to be called by a thread whose apartment state is STA (single-threaded apartment). Usually this is done by calling Thread.SetApartmentState, but in this case I don't know which thread is going to invoke my method.

How should I make the calling thread STA?


Solution

  • If your class is implementing those Begin/End pair methods as per an interface, then you have control over how the work is actually done. Delegates (of which Action is a typed generic of) will use the default thread pool I believe, and so will be performed by a shared re-usable available thread. Since messing with the thread pool isn't feasible, straight delegates are a no-go in this case.

    You'll have to create your own Thread object (passing in a new ThreadStart to your method) and set it's apartment state as you've already indicated. That method is simply going to have to have its own way to callback, since vanilla Threads don't provide a convenient way to my knowledge.

    You could also optionally use Tasks along with a custom StaTaskScheduler if you're using .NET 4.0, but this could be more trouble and/or complication than it's worth since it adds a lot of dependencies. It does eliminate the callback problem, though.