【发布时间】:2018-09-20 03:02:01
【问题描述】:
我有以下代码,它需要花费大量时间。我想有 4 个线程从文件中读取 id,然后转储由 ConnectToServiceAndDump 完成的详细信息。因为所有 id 都是唯一的,所以我可以用 4 个线程拿起 4 个唯一 id 并调用 ConnectToServiceAndDump。 我已经尝试过 Threading 类将线程数设置为 4 ,但是如果我将其保留在 while 循环中,这将不起作用。我仍然是线程新手,所以不确定什么是正确的方法。
或者类似这样的方法:
//- create a list.. which contains all the ids
//- create a new thread
//- in a theard safe way pop a loan from list
//- dump this id by calling service in the same thread
//- use ConcurrentQueue(T) and Enqueue
using (StreamReader sr = new StreamReader($@"{File}"))
{
var ids = sr.ReadLine();
while (ids != null)
{
ConnectToServiceAndDump(client, ids, outputSubdirectoryName);
ids = sr.ReadLine();
}
}
【问题讨论】:
-
读入所有的 id,然后使用
Parallel.ForEach或者只是简单的任务来排队所有的工作?
标签: c# multithreading file thread-safety threadpool