2011-04-22 76 views
1

我有,我用我的机器人Web客户端:锁定Web客户端 - 多线程应用程序

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; 
     } 
    } 

} 

我有我的Web客户端的一个对象。 有很多方法使用它。如果两个线程想要使用该webClient进行下载,我得到的错误表明webClent当时只能运行一个操作。 如何修改该类,以便当一个线程正在使用它时,另一个线程必须等待。 我需要以某种方式锁定它。

+0

既然你不希望他们同时运行,为什么不使用队列? http://www.dotnetperls.com/queue – Prix 2011-04-22 15:10:05

+0

@Prix所有线程都在做任务,等待,计数。有时候这些线程需要从页面中删除一些html。我非常罕见,但有时会发生2线程想要同时下载页面的情况。我想锁定,以便当时只有一个人可以使用该WebClient。 – Hooch 2011-04-22 16:12:24

回答

0

例如,您可以使用Mutex。
当第一个客户端发出请求时,您将获得互斥锁的属性,并在呼叫完成时释放它。
当其他客户端发出请求时,首先等待互斥锁并完成任务。