在 C# 中使用线程或队列写入文件
Writing to a File using threading or queue in c#
我有以下代码,它占用了很多 time.I 考虑有 4 个线程,它们将从文件中读取 ID,然后转储由 ConnectToServiceAndDump.Since 完成的详细信息 所有 ID 都是唯一的我可以接受 4 个线程获取 4 个唯一 ID 并调用 ConnectToServiceAndDump。
我已经尝试使用 Threading class 将线程数设置为 4 ,但是如果我将它保留在 loop.I 仍然是线程的新手所以不确定什么是正确的方法。
或者类似这样的方法:
//- 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();
}
}
var ids = new List<string>();
using (StreamReader sr = new StreamReader($@"{File}"))
{
var id = sr.ReadLine();
while (id != null)
{
ids.Add(id);
id = sr.ReadLine();
}
}
Parallel.ForEach(ids, (id) => ConnectToServiceAndDump(client, id, outputSubdirectoryName));
我有以下代码,它占用了很多 time.I 考虑有 4 个线程,它们将从文件中读取 ID,然后转储由 ConnectToServiceAndDump.Since 完成的详细信息 所有 ID 都是唯一的我可以接受 4 个线程获取 4 个唯一 ID 并调用 ConnectToServiceAndDump。 我已经尝试使用 Threading class 将线程数设置为 4 ,但是如果我将它保留在 loop.I 仍然是线程的新手所以不确定什么是正确的方法。
或者类似这样的方法:
//- 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();
}
}
var ids = new List<string>();
using (StreamReader sr = new StreamReader($@"{File}"))
{
var id = sr.ReadLine();
while (id != null)
{
ids.Add(id);
id = sr.ReadLine();
}
}
Parallel.ForEach(ids, (id) => ConnectToServiceAndDump(client, id, outputSubdirectoryName));