【问题标题】:Writing to a File using threading or queue in c#在 C# 中使用线程或队列写入文件
【发布时间】: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


【解决方案1】:
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));

【讨论】:

  • 谢谢迈克尔。它起作用了。在其中添加了新的 ParallelOptions { MaxDegreeOfParallelism = 4 }。
猜你喜欢
  • 1970-01-01
  • 2021-08-29
  • 2010-11-15
  • 1970-01-01
  • 1970-01-01
  • 2015-11-02
  • 1970-01-01
  • 2013-03-14
  • 2023-03-13
相关资源
最近更新 更多