this works:
//delegate
Parallel.For(1023456789, 1033456789, delegate(long i)
{
if (i % 10000000 == 0) Console.WriteLine("{0:N0}", i);
if (IsPanDigital(i))
{
list.Add(i);
}
}
);
//lambda expression
Parallel.For(1023456789, 1033456789, i =>
{
if (i%10000000 == 0) Console.WriteLine("{0:N0}", i);
if (IsPanDigital(i))
{
list.Add(i);
}
}
);
Is it possible to rewrite this logic using a Func? I’ve tried here..doesn’t compile.
var list = new List<long>();
Parallel.For(1023456789, 1033456789, Blah(i, ref list));
public static Func<long> Blah(long i, ref List<long> list)
{
if (i % 10000000 == 0) Console.WriteLine("{0:N0}", i);
if (IsPanDigital(i))
{
list.Add(i);
}
}
Am trying to see if it can be done.
You nearly had it:
(I changed
Blah‘s return type tovoid, and addi =>to wrap it in a lambda so it can matchAction<long>)Edit: Or change
BlahtoAction<long>and do some other minor refactoring:I think this second example is closer to what you were trying to achieve.
As @lee pointed out, the
refparameter, at least in the code you’ve shown, is not needed.refparameters also can’t be used inside lambdas, which caused a compiler error, so I removed it. If you really need to useref, go for the first example.The reason you can’t use
Funcis because aFunc<T>is something that returns aTvalue, andParallelis looking for anAction<T>, which returns void.@dtb pointed out something very important: “Note that adding to a list from multiple threads in parallel is not thread-safe.” You might be able to fix this by putting a lock around your
list.Addmethod, locking to aprivate static object. I would guess the vast majority of your work is in calculatingIsPanDigital, so I think this makes sense.