c# - 如何在 C# 中使用多线程时循环列表

标签 c# multithreading loops

我在使用多线程时有一个要循环的列表,我将获取列表的第一项并进行一些处理,然后删除该项。 当List的个数不大于0时,从data中取数据。

一句话: 在我的数据库中有很多记录。我需要将它们发布到我的服务器。在发布过程中,需要多线程,线程数可能是10个或更少。

例如:

private List<string> list;

void LoadDataFromDatabase(){
  list=...;//load data from database...
}

void DoMethod()
{
  While(list.Count>0)
  {
    var item=list.FirstOrDefault();
    list.RemoveAt(0);
    DoProcess();//how to use multi-thread (custom the count of theads)?
    if(list.Count<=0)
    {
     LoadDataFromDatabase();
    }
  }
}

请帮助我,我是c#的初学者,我已经搜索了很多解决方案,但没有类似的。

还有,我需要自定义广告的数量。

最佳答案

您对列表的处理应该按顺序进行吗?换句话说,当元素 n 的处理尚未完成时,不能处理元素 n + 1 吗?如果是这种情况,那么多线程 不是正确的解决方案。

否则,如果您的处理元素完全独立,您可以使用m个线程,为每个线程分配Elements.Count/m个元素继续努力

示例:打印列表:

List<int> a = new List<int> { 1, 2, 3, 4,5 , 6, 7, 8, 9 , 10 };
int num_threads = 2;
int thread_elements = a.Count / num_threads;

// start the threads
Thread[] threads = new Thread[num_threads];
for (int i = 0; i < num_threads; ++i)
{
  threads[i] = new Thread(new ThreadStart(Work));
  threads[i].Start(i);
}
// this works fine if the total number of elements is divisable by num_threads
// but if we have 500 elements, 7 threads, then thread_elements = 500 / 7 = 71
// but 71 * 7 = 497, so that there are 3 elements not processed
// process them here:
int actual = thread_elements * num_threads;
for (int i = actual; i < a.Count; ++i)
   Console.WriteLine(a[i]);

// wait all threads to finish
for (int i = 0; i < num_threads; ++i)
{
  threads[i].Join();
}

void Work(object arg)
{
  Console.WriteLine("Thread #" + arg + " has begun...");

  // calculate my working range [start, end)
  int id = (int)arg;
  int mystart = id * thread_elements;
  int myend = (id + 1) * thread_elements;

  // start work on my range !!
  for (int i = mystart; i < myend; ++i)
      Console.WriteLine("Thread #" + arg + " Element " + a[i]);
}

ADD 对于您的情况(上传到服务器),它与上面的代码相同。您分配了多个线程,为每个线程分配了元素数量(这是在变量 thread_elements 中自动计算的,因此您只需更改 num_threads)。对于方法 Work,您只需将行 Console.WriteLine("Thread #"+ arg + "Element "+ a[i]); 替换为上传代码.

还有一点要记住,多线程取决于您的机器 CPU。例如,如果您的 CPU 有 4 个内核,那么获得的最佳性能将是最多 4 个线程,以便为每个内核分配一个线程。否则,如果您有 10 个线程,例如,它们会比 4 个线程慢,因为它们会在 CPU 内核上竞争(除非线程空闲,等待某些事件发生(例如上传)。在这种情况下,10 个线程可以运行,因为它们不会占用 %100 的 CPU 使用率)

警告:不要在任何线程工作时修改列表(添加、删除、设置元素...),也不要为两个线程分配相同的元素。这样的事情会给你带来很多错误和异常!!!

关于c# - 如何在 C# 中使用多线程时循环列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21872333/

相关文章:

c# - 使用动态属性初始化惰性属性

c# - asp.net mvc中依赖解析和IoC的优势

只有 put 和 get 的 Java HashMaps - 可能存在并发问题?

c - 最多20个30位数字的乘法

c# - 是否可以使用反序列化进行构造函数注入(inject)?

c# - VS2010 : Automatically insert date and initials to single line comments

linux - 多线程与多进程

c# - 如果您只是在之后立即调用 End,为什么还要调用 WaitOne? End 不阻塞吗?

javascript - for循环导致页面崩溃

python - 每 'n' 次迭代暂停循环并等待用户按键。 - Python