Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Context across threads in async WCF REST service

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:

  1. Is there any safe way to propagate OperationContext and/or HttpContext to the new thread?
  2. If I am able to modify the legacy code to move away from OperationContext and HttpContext, is there a recommended way to share context information across threads in a WCF setting?
like image 818
BitMask777 Avatar asked Nov 10 '22 15:11

BitMask777


1 Answers

  1. 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...

  2. 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.

like image 72
Phil Degenhardt Avatar answered Nov 14 '22 23:11

Phil Degenhardt