我正在尝试编写一个 C# 函数来使用 http 请求来计算网页上损坏的链接。因为我想加快速度,所以我为每个请求创建一个线程,然后简单地增加线程中的计数器。我的问题是,尽管我知道网站上有几个损坏的链接,但计数器最后仍保持为 0。似乎线程没有在主线程中设置变量。
public volatile int found;
public volatile int notfound;
public void GetBrokenLinks(WebBrowser website)
{
HtmlElementCollection links = website.Document.GetElementsByTagName("a");
foreach (HtmlElement element in links)
{
string link = element.GetAttribute("href").ToString();
Uri urlCheck = new Uri(link);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(urlCheck);
request.Timeout = 10000;
try
{
Thread link_checher_thread = new Thread(delegate ()
{
HttpWebResponse response;
response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
{
response.Dispose();
found++;
}
else if (response.StatusCode == HttpStatusCode.NotFound)
{
response.Dispose();
notfound++;
}
});
link_checher_thread.IsBackground = true;
link_checher_thread.Start();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
MessageBox.Show(found.ToString() + ", " + notfound.ToString());
}
我在互联网上搜索了几个小时,尝试了 volatile 变量,但似乎没有任何效果。我如何强制线程在主线程中设置变量?
最佳答案
在.NET中增加共享计数器的正确方法是通过System.Threading.Interlocked.Increment(引用找到)
关于c# - 如何从 C# 中的另一个线程在主线程中设置变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35374330/