Skip to content

Clarify CookieContainer thread-safety #11171

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Apr 23, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions xml/System.Net/CookieContainer.xml
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,14 @@

The <xref:System.Net.CookieContainer> has three properties that govern the volume of the content of the container: <xref:System.Net.CookieContainer.Capacity%2A>, <xref:System.Net.CookieContainer.MaxCookieSize%2A>, and <xref:System.Net.CookieContainer.PerDomainCapacity%2A>. These values have the default settings of 300, 4096, and 20 respectively. When a <xref:System.Net.Cookie> is added to the container, these properties are used to determine whether a <xref:System.Net.Cookie> already contained in the <xref:System.Net.CookieContainer> should be discarded to make room for the new one. The <xref:System.Net.CookieContainer> keeps track of each addition to ensure that neither the <xref:System.Net.CookieContainer.Capacity%2A> nor the <xref:System.Net.CookieContainer.PerDomainCapacity%2A> limits are exceeded. If one or both are exceeded, then <xref:System.Net.Cookie> instances held by the <xref:System.Net.CookieContainer> are removed. First, any expired <xref:System.Net.Cookie> is removed. If further capacity must be recaptured, then the least-recently used <xref:System.Net.CookieCollection> is purged.

## Thread Safety

The methods for adding and retrieving <xref:System.Net.Cookie> instances to and from a <xref:System.Net.CookieContainer> are thread-safe and can be used concurrently from multiple threads.

> [!NOTE]
> Regardless of thread-safety, unanticipated sharing of <xref:System.Net.CookieContainer> instances can lead to issues when working with <xref:System.Net.Http.HttpClient> and <xref:System.Net.Http.HttpClientHandler> or <xref:System.Net.Http.SocketsHttpHandler>, since parts of the application that aren't intended to share cookies with each other might inadvertently do so.
> It is not recommended to use cookies together with <xref:System.Net.Http.IHttpClientFactory>.

]]></format>
</remarks>
<altmember cref="T:System.Net.Cookie" />
Expand Down