我已经从SO中读过几个关于此问题的不同问题,但仍然没有能够让它发挥作用。我使用public static string[] files = Directory.GetFiles(CurrentDirectory, "*.wav", SearchOption.AllDirectories);
获取一个文件路径数组,然后将其传递给文件流。只有一个线程处理所有文件,文件流所做的操作耗时太长。所以我决定拆分数组并将这些较小的数组传递给不同的线程。
我使用的代码是我从另一个SO问题中得到的,并用它来传递split数组,但它只能用于第一个数组中的一个文件,但我知道问题是什么:
var thing = from index in Enumerable.Range(0, files.Length)
group files[index] by index/600;
foreach(var set in thing)
string.Join(";", set.ToArray());
(这并不是我如何使用它,我已经把它弄得太乱了,我无法记住。)这个问题是所有东西都被视为一个巨大的文件路径,我有一个foreach循环,从较小的数组中获取每个文件,但它只将其中的每个文件视为一个,当搜索返回多个文件时抛出filepathtoolong异常。我的函数接受一个数组,然后使用foreach (string file in smallerArray)
写入每个数组。我需要做的是将文件数组拆分为4个较小的数组并启动新的线程,如new Thread(() => { DoWork(newArray); }).Start();
,但我尝试过的任何工作都没有。
答案 0 :(得分:5)
所以我决定拆分数组并将那些较小的数组传递给不同的线程。
听起来你正在努力做到这一点:)让框架为你处理Parallel.ForEach
:
Parallel.ForEach(files, file =>
{
// Do stuff with one file
});
答案 1 :(得分:0)
这是示例
public static IEnumerable<IEnumerable<T>> Split<T>(this IEnumerable<T> source, int blockSize)
{
if (source == null)
throw new ArgumentNullException("source");
if (blockSize <= 0)
throw new ArgumentException("blockSize = {0}".FormatWith(blockSize), "blockSize");
var result = new List<IEnumerable<T>>();
for (int blockStartIndex = 0; blockStartIndex < source.Count(); blockStartIndex += blockSize)
{
int blockStart = blockStartIndex;
int blockEnd = blockStartIndex + blockSize - 1;
IEnumerable<T> block = source.Where((x, i) => i >= blockStart && i <= blockEnd);
result.Add(block);
}
return result;
}
这是测试
[Test]
public void TestSplit()
{
var list = new[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
IEnumerable<IEnumerable<int>> splitted = list.Split(10);
Assert.That(splitted.Count(), Is.EqualTo(1));
Assert.That(splitted.First().Count(), Is.EqualTo(10));
splitted = list.Split(11);
Assert.That(splitted.Count(), Is.EqualTo(1));
Assert.That(splitted.First().Count(), Is.EqualTo(10));
splitted = list.Split(9);
Assert.That(splitted.Count(), Is.EqualTo(2));
Assert.That(splitted.First().Count(), Is.EqualTo(9));
Assert.That(splitted.ElementAt(1).Count(), Is.EqualTo(1));
splitted = list.Split(3);
Assert.That(splitted.Count(), Is.EqualTo(4));
Assert.That(splitted.First().Count(), Is.EqualTo(3));
Assert.That(splitted.ElementAt(1).Count(), Is.EqualTo(3));
Assert.That(splitted.ElementAt(2).Count(), Is.EqualTo(3));
Assert.That(splitted.ElementAt(3).Count(), Is.EqualTo(1));
}