I'm creating an async REST API using a 202 approach. I have to implement this in WCF (not Web API) and my plan is to spawn a new thread to perform the async work while letting the WCF operation thread return the 202. The issue I'm running into is that some legacy code that I need to use in the new thread is expecting OperationContext and HttpContext to store and retrieve context information. I know that both of these are thread-specific and as a result are null in the spawned thread.
I have two questions:
You will be responsible for ensuring any threads you spawn receive the necessary context. WCF only takes responsibility for ensuring OperationContext flows with any thread switching it initiates, which is why an IExtension<OperationContext>
is the recommended method for storing contextual data. Once you leave the building, you're on your own...
For spawning tasks on the thread pool, the typical approach would be to prepare any necessary context information and then pass that through to the delegate e.g. Task.Run(() => doLongRunningTask(contextCopiedFromOperationContext))
. The delegate, would then be responsible for populating ThreadLocal<T>
objects (or whatever mechanism you wish to use) before invoking the actual long running implementation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With