1

In .net 4, Is it possible to store custom value such as userid in Thread.CurrentThread object?

I am trying to store userid for wcf client on the client side of MessageInspector in AfterReceiveRequest method as follows:

request.Headers.Add(MessageHeader.CreateHeader("userid", string.Empty, userid));

On the server side I would like to retrieve it in a Thread.CurrentThread in the method AfterReceiveRequest.

Is this possible?

John Saunders
  • 160,644
  • 26
  • 247
  • 397
dotnet-practitioner
  • 13,968
  • 36
  • 127
  • 200
  • 1
    If you go asynchronous (fairly common in .net 4.5) this may prove to be a problematic way of doing things, because the thread servicing your code could be one of any in the thread pool – spender Sep 07 '12 at 17:11
  • 1
    Why don't you go to the headers collection on OperationContext.Current on the server? – lgoncalves Sep 07 '12 at 19:56
  • possible duplicate of [Where to store data for current WCF call? Is ThreadStatic safe?](http://stackoverflow.com/questions/1895732/where-to-store-data-for-current-wcf-call-is-threadstatic-safe) – Christian.K Sep 10 '12 at 06:50

1 Answers1

2

ThreadStatic is not recommended because WCF will randomly use threads from the thread pool and ThreadStatic variables will not be reinitialized when the threads are recycled. Also if you have a session with multiple WCF calls, the same service instance is likely to switch threads from call to call.

You should create an OperationContext extension.

See Where to store data for current WCF call? Is ThreadStatic safe?

Community
  • 1
  • 1
ErnieL
  • 5,773
  • 1
  • 23
  • 27