0

I have a legacy WCF web service that uses BasicHttpBinding and is hosted in IIS.

The web service Operation methods use ThreadStatic fields to hold state data that is used during the processing of the request.

I want to clean up these ThreadStatic fields when each Operation is completed, so that values don't "leak" to code that may subsequently use the same thread pool thread.

I naively thought I would be able to do this in Application_EndRequest in global.asax; but that doesn't work as it seems it runs on a different thread.

So I'm considering an alternative approach, which is to use an IDispatchMessageInspector, and clean up the ThreadStatic values in its BeforeSendReply method.

Before doing so, I would like to know if it is guaranteed that BeforeSendReply will be executed on the same thread as the Operation method. Can anyone tell me if this is guaranteed, and if so point to an authoritative reference that confirms it?

Joe
  • 122,218
  • 32
  • 205
  • 338
  • change your thread static members to members at class level and then use InstanceContextMode to specify the life cycle of the WCF class instance. once you set the instance mode to percall or persession, your members will be cleaned up at the end of the call or session. – Dhawalk Aug 31 '17 at 17:37
  • @Dhawalk, Not all classes involved are used exclusively from WCF, so that's unfortunately not an option. Nor is extending `OperationContext` as described here: https://stackoverflow.com/questions/1895732/where-to-store-data-for-current-wcf-call-is-threadstatic-safe/1895958#1895958 – Joe Aug 31 '17 at 18:24

0 Answers0