gpt4 book ai didi

c# - 如何制作 CookieContainer 的副本?

转载 作者:行者123 更新时间:2023-11-30 13:16:58 24 4
gpt4 key购买 nike

鉴于 CookieContainer 的实例是 not thread safe .

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

事实证明,我不能在没有同步的情况下跨多个并发 HTTP 请求使用同一个容器。不幸的是,从 MSDN 的文档中,并不清楚如何正确地同步它。

解决方案是为每个请求使用主容器的副本,一旦请求完成,副本中的 cookie 可以合并回主容器。创建副本和合并可以以同步方式完成。

所以问题是:如何复制 CookieContainer 类的实例?

最佳答案

CookieContainer 类是可序列化的。既然你说你无论如何都需要序列化它,为什么不直接使用 BinaryFormatter 将它序列化为 MemorySteam,然后反序列化它以制作副本?

我知道这太简单了,如果没有帮助请忽略。

private CookieContainer CopyContainer(CookieContainer container)
{
using(MemoryStream stream = new MemoryStream())
{
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(stream, container);
stream.Seek(0, SeekOrigin.Begin);
return (CookieContainer)formatter.Deserialize(stream);
}
}

关于c# - 如何制作 CookieContainer 的副本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18300171/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com