c# - 如何从 C# 中的另一个线程在主线程中设置变量?

标签 c# multithreading

我正在尝试编写一个 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/

相关文章:

c# - C#中的每线程内存管理

c# - .Net Core 控制台应用程序中未找到依赖项 - 启动时显示为缺失

c# - 使用 C# 运行交互式命令行 exe

java - 代码中的 IllegalMonitorStateException

java - Drools 单例 StatefulKnowledgeSession 作为 Web 服务

java - Spring Autowiring 线程类

c# - 派生类对象在内存中是什么样子的?

C# : How to resize image proportionately with max height

java - 共享进程/线程

java - Android 线程间的数据流