锁定 WebClient - 多线程应用程序
我在我的机器人中使用了 webClient:
using System;
using System.Net;
namespace Game_Bot
{
class WebClientEx : WebClient
{
public CookieContainer CookieContainer { get; private set; }
public WebClientEx()
{
CookieContainer = new CookieContainer();
}
public void ClearCookies()
{
CookieContainer = new CookieContainer();
}
protected override WebRequest GetWebRequest(Uri address)
{
var request = base.GetWebRequest(address);
if (request is HttpWebRequest)
{
(request as HttpWebRequest).CookieContainer = CookieContainer;
}
return request;
}
}
}
我有一个 webclient 对象。 有很多使用它的方法。如果两个线程想要使用该 webClient 进行下载,我会收到错误消息,指出 webClent 一次只能运行一项操作。 我如何修改该类,以便当一个线程使用它时,另一个线程必须等待。 我需要以某种方式锁定它。
I have webClient that I am using in my bot:
using System;
using System.Net;
namespace Game_Bot
{
class WebClientEx : WebClient
{
public CookieContainer CookieContainer { get; private set; }
public WebClientEx()
{
CookieContainer = new CookieContainer();
}
public void ClearCookies()
{
CookieContainer = new CookieContainer();
}
protected override WebRequest GetWebRequest(Uri address)
{
var request = base.GetWebRequest(address);
if (request is HttpWebRequest)
{
(request as HttpWebRequest).CookieContainer = CookieContainer;
}
return request;
}
}
}
I have one object of my webclient.
There are many methods that use it. If two threads want to use that webClient to download I got error saying that webClent can run only one operation at the time.
How can I modify that class so that when one thread is using it the other one have to wait.
I need to lock it in some way.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用锁定语句。
You can use the lock statement.
例如,您可以使用互斥锁。
当第一个客户端发出请求时,您将获得互斥体的属性,并在调用完成时释放它。
当其他客户端发出请求时,首先等待互斥锁,然后工作就完成了。
You could use a Mutex for example.
When first client makes a request, you get the property of the mutex, releasing it when the call completes.
When other clients make request, first you wait for mutex and the job is done.