Home > Net >  HttpClient singleton thread-safe
HttpClient singleton thread-safe

Time:03-25

When using HttpClient said generally want to use the singleton pattern, just think of whether thread-safe, multiple threads to get the same instance, for the same instance operation, will not affect each other?
Just do a simple test,

 
The static readonly HttpClient client=new HttpClient ();
The static void Main (string [] args)
{
(A);
Thread.Sleep(1000);
(B);

Console.ReadLine();
}

Public static void (A)
{
New Thread (()=& gt;
{
Client. DefaultRequestHeaders. Add (" a ", "a");
Console. WriteLine (" (A) set A ");
Thread.sleep (10000);
Console. WriteLine (" (A) sleep stop ");
}). The Start ();

}
Public static void (B)
{
Console. WriteLine (" (B) start ");
If (client. DefaultRequestHeaders. The Contains (" a "))
Console. WriteLine (" has a ");

Console. WriteLine (" (B) end ");
}


The results
(A) set A
(B) start
From a
(B) end
(A) sleep stop
Execution result shows that the thread is unsafe,

With MultiThreadedHttpConnectionManager ensure thread safety in Java, c # in how to deal with? Or did I understand there is a problem?

CodePudding user response:

Now that to change the header, and that is another example (also can be another singleton?)
  •  Tags:  
  • C#
  • Related