1

我构建了一个应用程序,它通过下载 URL 的内容来查询 API。每次下载都在它自己的线程中使用以下代码进行:

    public void run(int id, string requestURL)
    {
        var filePath = "data\\" + id + ".xml";
        (new FileInfo(filePath)).Directory.Create();
        WebClient client = new WebClient();
        client.DownloadFile(requestURL, filePath);

        // code to parse file
    }

我注意到这些文件中的每一个都没有同时加载。

我已经在这里看到了一些这样的问题,但在所有这些情况下,每次下载只运行一次。就我而言,我需要它在完成后立即重新运行下载。

我怎样才能实现这样的目标?

编辑:我用来创建线程的代码:

    public void startRun(object thread)
    {
        Threads t = (Threads)thread;
        DoRun DoRun = new DoRun(this);
        string kwd = t.keyword;
        t.requestUrl = DoRun.returnUrl(System.Uri.EscapeDataString(kwd));
        while (checkRunning())
        {
            DoRun.run(t.id, t.requestUrl);
        }
    }

    private void startBtn_Click(object sender, EventArgs e)
    {
        searchRunning = true;

        XmlDocument searches = new XmlDocument();
        searches.Load("data\\Searches.xml");

        XmlNodeList search = searches.SelectNodes("searches/search");
        var nodeCount = search.Count;
        for (var i = 0; i < nodeCount; i++)
        {
            Threads thisThread = new Threads();
            thisThread.keyword = search[i].SelectSingleNode("query").InnerText;
            thisThread.id = int.Parse(search[i].SelectSingleNode("id").InnerText);

            Thread newThread = new Thread(() => startRun(thisThread));

            newThread.Name = "SearchId: " + i;
            newThread.IsBackground = true;
            thisThread.thread = newThread;
            threads.Add(thisThread);
            newThread.Start();
        }
    }
4

0 回答 0