Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is .NET System.Net.CookieContainer thread safe?

  1. Is the .NET class System.Net.CookieContainer thread safe? --Update: Turnkey answered--
  2. Is there any way to ensure thread safeness to variables which are modified during asynchronous requests (ie. HttpWebRequest.CookieContainer)?
  3. Is there any attribute to highlight thread safe classes? --Update: If thread-safeness is described on MSDN then probably they don't have an attribute for this --
  4. Are all .NET classes thread safe? --Update: Marc answered--

I ask these questions because I use the CookieContainer in asynchronous requests in a multithreaded code. And I can't put an asynchrounous request inside a lock. Maybe I'll have to use readonly "variables" (or immutable types) like in F#, right?

like image 211
Jader Dias Avatar asked Dec 28 '08 14:12

Jader Dias


2 Answers

No, not all .NET classes are thread safe. In fact, very few have a need to be. In general, static members should be thread-safe, but that is about it.

Immutable / semi-immutable objects are automatically thread safe (this includes things like XslTransform etc) - and there are a mutable few cases (such as threaded containers) where you can expect things to be thread safe. MSDN states thread-safety for each class.

I would have no expectation for a cookie-container to be thread-safe, so you will probably have to synchronize this yourself.

(updated)

Re your second point; exactly which variables are you thinking of? Your own local state variables won't be directly updated during the async request, so it simply falls to you to synchronize access when preparing requests are when processing responses. Most commonly, via a Monitor - i.e.

lock(syncLock) {
    // prepare request from (synchronized) state
    req.Begin{...}
}

and then in the callback

lock(syncLock) {
    // ...read values from request...
    // ...update local state...
}

Where syncLock is just a lock object (perhaps held against an instance):

private readonly object syncLock = new object();
like image 158
Marc Gravell Avatar answered Oct 07 '22 19:10

Marc Gravell


From the horses mouth:

Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Edit:

You could put a lock around actions that modify the instance members.

like image 45
Turnkey Avatar answered Oct 07 '22 19:10

Turnkey