0

I would like to do this with Parallel.ForEach. how can I do?

partial class Form1: Form
{
private List<my_class> lstmy_class = new List<my_class>();  

private void execute_tpl(object source, ElapsedEventArgs e)
    {
        var tokenSource = new CancellationTokenSource();
        var token = tokenSource.Token;
        var tab_task = new Task[lstmy_class.Count];
        try
            {
                for (int i = 0; i < lstmy_class.Count; i++)
                {
                   tab_task[i] = Task.Factory.StartNew(() => lstmy_class[i].Calcul(token));
                }

                Task.WaitAll(tab_task);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error : "+ex.GetType());
            }
    }
}

class my_class{ 
... 
    public void Calcul(CancellationToken token)
    {
       // do work       
    }   
}

I try with :

Parallel.ForEach<my_class>(lstChartClass, () => Calcul(token));

but the compiler don't want this syntax. I don't find the good syntax.

I try also with Parallel.ForEach<my_class>(lstChartClass, (i) => lstChartClass[i]Calcul()); but nothing works.

0

1 Answer 1

1

The second parameter of Parallel.ForEach is an Action<TSource>, meaning that it must be a delegate that returns nothing but takes a TSource as a parameter. Therefore, the syntax for your case would be

Parallel.ForEach(lstmy_class, n => n.Calcul(token));
Sign up to request clarification or add additional context in comments.

1 Comment

@Florent You're welcome! If this solved your problem, you can accept my answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.