.NET System.Net.CookieContainer线程安全吗? [英] Is .NET System.Net.CookieContainer thread safe?

查看:137
本文介绍了.NET System.Net.CookieContainer线程安全吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  1. .NET类System.Net.CookieContainer线程安全吗? -更新:交钥匙----
  2. 有什么方法可以确保异步请求期间修改的变量(例如HttpWebRequest.CookieContainer)的线程安全性?
  3. 是否有任何属性可以突出显示线程安全类? -更新:如果在MSDN上描述了线程安全性,那么他们可能对此没有属性-
  4. 所有.NET类都是线程安全的吗? -更新:马克回答了-
  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--

我问这些问题是因为我在多线程代码的异步请求中使用CookieContainer.而且我不能在锁中放入非常规请求.也许我必须像F#中那样使用只读的变量"(或不可变类型),对吧?

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?

推荐答案

否,并非所有.NET类都是线程安全的.实际上,几乎没有必要如此.通常,静态成员应该是线程安全的,但仅此而已.

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.

不可变/半不变对象自动是线程安全的(这包括XslTransform等)-在少数情况下(例如线程容器),您可以期望它们是线程安全的. MSDN规定了每个类的线程安全性.

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.

我不希望cookie容器具有线程安全性,因此您可能必须自己进行同步.

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

(已更新)

再说第二点;您到底在考虑哪些变量?您自己的局部状态变量不会在异步请求期间直接更新,因此在准备请求时或处理响应时,您就只能由您来同步访问.最常见的是通过Monitor-即

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{...}
}

然后在回调中

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

syncLock只是一个锁定对象(可能针对实例保留):

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

private readonly object syncLock = new object();

这篇关于.NET System.Net.CookieContainer线程安全吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆