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?
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();
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With