1

I am reusing same HttpClient throughout the application. But i have to set different headers for different users.

I have referred this post : HttpClient single instance with different authentication headers

When I implemented this approach and runs code concurrently, like this : Parallel.For(0, 3, i => { // HttpClient Call } Thread overrides each other data. Could you please let me know how to fix it ?

Thanks in Advance.

Community
  • 1
  • 1
user2266837
  • 587
  • 2
  • 5
  • 12
  • Most straightforward way would be to use a new HttpClient per thread using a thread-local storage as described here: https://msdn.microsoft.com/en-us/library/dd783586(v=vs.110).aspx. – Clay Jan 02 '17 at 14:50
  • @clay : I want to use single instance of http client. When multiple users try to access http client then we can set http client header according to user details. – user2266837 Jan 02 '17 at 15:16
  • Is each thread writing to the default headers, or making new request-specific headers on each call as described in the accepted answer? If it's "overrides each other's data", then it sounds like you're writing the headers into the HttpClient and not the request. – Clay Jan 02 '17 at 15:32
  • I am writing in http request message but still it overwrites. – user2266837 Jan 02 '17 at 16:04
  • Hmmm...never used it the way specified in the article. It is possible that, although accepted, it doesn't work that way. I'm not sure there's a compelling reason to have one long-lived HttpClient. My preference would be to let the shared initializer on Parallel.For create one per thread...but maybe somebody has more info. Consider sharing your existing Parallel.For body code and maybe we can discover something. – Clay Jan 02 '17 at 16:18
  • @Clay `HttpClient` is a shareable and thread-safe object and designed to be singleton accroding to [this](https://learn.microsoft.com/en-us/azure/architecture/antipatterns/improper-instantiation/). Create/Destory will bring performance impact. @user2266837 you need to provide your minimal codes. – joe Jun 08 '18 at 08:52

0 Answers0