我正在使用定時web客戶端的項目。類結構就是這樣。c#爲什麼當WebClient通過線程調用時,WebClient超時大部分時間?
Controller =>主要類的主管 Form1,SourceReader,ReportWriter,UrlFileReader,HTTPWorker,TimedWebClient。
HTTPworker是在獲得url時獲取頁面源的類。 TimedWebClient是處理WebClient超時的類。這是代碼。
class TimedWebClient : WebClient
{
int Timeout;
public TimedWebClient()
{
this.Timeout = 5000;
}
protected override WebRequest GetWebRequest(Uri address)
{
var objWebRequest = base.GetWebRequest(address);
objWebRequest.Timeout = this.Timeout;
return objWebRequest;
}
}
在HTTPWorker我有
TimedWebClient wclient = new TimedWebClient();
wclient.Proxy = WebRequest.GetSystemWebProxy();
wclient.Headers["Accept"] = "application/x-ms-application, image/jpeg, application/xaml+xml, image/gif, image/pjpeg, application/x-ms-xbap, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*";
wclient.Headers["User-Agent"] = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; MDDC)";
string pagesource = wclient.DownloadData(requestUrl);
UTF8Encoding objUTF8 = new UTF8Encoding();
responseData = objUTF8.GetString(pagesource);
我已經有處理的異常。 在Form1中我有一個背景控制器和一個urllist。
首次執行:
首先,我花了一個網址的時間和給了它唯一的控制器對象的過程。 然後它工作正常。但是,由於它是連續的,因此列表太長時,花了很長時間。
第二實例:
然後在的BackgroundWorker的Do_Work我七次控制器和七根絲線。每個控制器都有唯一的HTTPWorker對象。但現在它拋出異常說「超時」。
以下是Form1.cs backgroundworker1_DoWork中的代碼。
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
bool done = false;
while (!backgroundWorker1.CancellationPending && !done)
{
int iterator = 1;
int tempiterator = iterator;
Controller[] cntrlrarray = new Controller[numofcontrollers];
Thread[] threadarray = new Thread[numofcontrollers];
int cntrlcntr = 0;
for (cntrlcntr = 0; cntrlcntr < numofcontrollers; cntrlcntr++)
{
cntrlrarray[cntrlcntr] = new Controller();
}
cntrlcntr = 0;
for (iterator = 1; iterator <= this.urlList.Count; iterator++)
{
int assignedthreads = 0;
for (int threadcounter = 0; threadcounter < numofcontrollers; threadcounter++)
{
cntrlcntr = threadcounter;
threadarray[threadcounter] = new Thread(() => cntrlrarray[cntrlcntr].Process(iterator - 1));
threadarray[threadcounter].Name = this.urlList[iterator - 1];
threadarray[threadcounter].Start();
backgroundWorker1.ReportProgress(iterator);
assignedthreads++;
if (iterator == this.urlList.Count)
{
break;
}
else
{
iterator++;
}
}
for (int threadcounter = 0; threadcounter < assignedthreads; threadcounter++)
{
cntrlcntr = threadcounter;
threadarray[threadcounter].Join();
}
if (iterator == this.urlList.Count)
{
break;
}
else
{
iterator--;
}
}
done = true;
}
}
這是什麼原因和解決方案? Appolgises太長。先謝謝你。
先用較少的線程嘗試一下。最有可能的地方有一個限制(4個同時連接)。通過MaxDegree選項而不是Thread對象來使用'Parallel.ForEach()'。 –