我在使用多线程时有一个要循环的列表,我将获取列表的第一项并进行一些处理,然后删除该项。 当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/