我正在尝试验证来自多个线程的URL并更新DataTable。 使用单个线程时,验证工作正常
工作正常 - 单线程
foreach (string url in urllist)
{
Boolean valid = CheckURL(url);
this.Invoke((MethodInvoker)delegate()
{
if (valid)
{
dt.Rows[counter][2] = "Valid";
validcount++;
}
else
{
dt.Rows[counter][2] = statusCode;
invalidcount++;
}
counter++;
});
}
但是当我尝试使用多个线程时,一些有效的URls被报告为无效,反之亦然。
多线程 - 不工作
Parallel.ForEach(urllist, ProcessUrl);
private void ProcessUrl(string url)
{
Boolean valid = CheckURL(url);
this.Invoke((MethodInvoker)delegate()
{
if (valid)
{
dt.Rows[counter][2] = "Valid";
validcount++;
}
else
{
dt.Rows[counter][2] = statusCode;
invalidcount++;
}
counter++;
});
}
相关方法和类
private Boolean CheckURL(string url)
{
using (MyClient myclient = new MyClient())
{
try
{
myclient.HeadOnly = true;
myclient.Headers.Add(HttpRequestHeader.UserAgent, "My app.");
//fine, no content downloaded
string s1 = myclient.DownloadString(url);
statusCode = null;
return true;
}
catch (WebException error)
{
if (error.Response != null)
{
HttpStatusCode scode = ((HttpWebResponse)error.Response).StatusCode;
if (scode != null)
{
statusCode = scode.ToString();
}
}
else
{
statusCode = "Unknown Error";
}
return false;
}
}
}
class MyClient : WebClient
{
public bool HeadOnly { get; set; }
protected override WebRequest GetWebRequest(Uri address)
{
WebRequest req = base.GetWebRequest(address);
req.Timeout = 10000;
if (HeadOnly && req.Method == "GET")
{
req.Method = "HEAD";
}
return req;
}
}
我做错了什么?请指教..
更新
我如何开始任务 - >
var ts = new CancellationTokenSource();
CancellationToken ct = ts.Token;
Task.Factory.StartNew(() =>
{
if (nameresfailcount > 10)
{
if (ct.IsCancellationRequested)
{
// another thread decided to cancel
Console.WriteLine("task canceled");
break;
}
}
//stuff
},ct).ContinueWith(task =>
{
_benchmark.Stop();
}