我构建了一个应用程序,通过下载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();
}
}