我剛剛開始學習有關Parallel.For()在c#中,我有一個功能,做一些事情,我不知道如何調整它爲並行。 任何人都可以向我展示這種類似案例嗎?在c#中調整並行的函數#
更新:
for (int i = 0; i < (samples32array.Length); i += 35) //Delimiter Samples Length = SampleRate*DelimiterTimeLength,(i.e: 44100*0.2=8820 samples)
{
if ((i + (int)DelimiterSamplesCount - 1) > samples32array.Length)
{
break;
}
double power = MyGoertzel.GoertzelFilter(samples32array, i, i + (int)DelimiterSamplesCount - 1, coeffDelimiter);
if (power > max_power)
{
max_power = power;
max_power_index = i;
}
}
更新:這是我的tryings但事情錯了......
private int delimiter_search_Parallel(float[] samples32array, int DelimiterSamplesCount, double DelimiterFreq)
{
double normalizedfreqDelimiter = DelimiterFreq/44100;
double coeffDelimiter = 2 * Math.Cos(2 * Math.PI * normalizedfreqDelimiter);
double max_power = 0;
int max_power_index = 0;
List<double> powerParallelList = new List<double>();
List<int> powerParallelListIndex = new List<int>();
Parallel.For(0, samples32array.Length, (i, loopState) =>
{
if ((i + (int)DelimiterSamplesCount - 1) > samples32array.Length)
{
//TODO -> Genereate a Windows with ERROR Exception
loopState.Stop();
return;
}
else
{
double power = MyGoertzel.GoertzelFilter(samples32array, i, i + (int)DelimiterSamplesCount - 1, coeffDelimiter);
powerParallelList.Add(power);
powerParallelListIndex.Add(i);
}
}
);
max_power = powerParallelList.Max();
max_power_index = powerParallelListIndex[powerParallelList.IndexOf(max_power)];
return max_power_index;
}
你不能並行化。每次迭代都需要先前迭代的答案。 – SimpleVar
謝謝。現在明白了。 – axcelenator
你好@YoryeNathan,我更新了代碼。對不起,我放錯了一個 – axcelenator