Call 3 functions at the same time. Should Parallel.For be used?

Problem:

I am currently calling 3 functions inside my code that execute behind each other, which will take some time to finish. So I was wondering if there is a way to call them at the same time, for example using a loop Parallel.For.

If I could use a loop Parallel.For, how can I succeed? Will it be right?

Parallel.For(0, 1, i =>
{
    bool check1 = function1(address);
    bool check2 = function2(address);
    bool check3 = function3(address);
});

My current code is:

private void check()
{
    for (int i = 0; i < dataGridView1.RowCount; i++)
    {
        string address = dataGridView1.Rows[i].Cells[0].Value.ToString();

        try
        {
            if (address.Length < 6)
            {
                // Those 3 functions are currently called behind each other
                // Could those be called inside a Parallel.For loop at the same time?
                bool check1 = function1(address);
                bool check2 = function2(address);
                bool check3 = function3(address);
            }
            else
            {
                dataGridView1.Rows[i].Cells[2].Value = "Error";
            }
        }
        catch(Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }
}
+4
source share
1 answer

As a quick estimate (you will get a reasonable gain), you can try Parallel Linq (PLinq).

bool[] results = new Func<string, bool>[] {function1, function2, function3}
  .AsParallel()
  .AsOrdered() // <- to guarantee function / outcome correspondence
  .Select(f => f(address))
  .ToArray();  

bool check1 = results[0];
bool check2 = results[1];
bool check3 = results[2];   
+4
source

Source: https://habr.com/ru/post/1686819/


All Articles