How to invoke Action<String^> via Parallel::For

98 Views Asked by At

I would like to invoke an Action<String^ via Parallel::For but get the error below.

My code:

Action<String^> ^act =    gcnew Action<String^>(this, &Form1::loadFileInternam);

System::Threading::Tasks::Parallel::For(1, 16, act);
void loadFileInternam(String^ fn)
{
}

The error I get:

Error: Severity Code Description Project File Line Suppression State Error C2665 'System::Threading::Tasks::Parallel::For': none of the 8 overloads could convert all the argument types ddddd C:\Users\Jack\Desktop\repos\new_c++\Text editor - Copy\CppCLR_WinformsProject1 - Copy - Copy - Copy (2) - Copy (2)\Form1.h 1620

1

There are 1 best solutions below

2
On

The Problem:

As you can see here, according to the list of overloads Parallel::For support several types of Action, but none of them accepts a String argument.

A Solution:

It is not clear what you actually intended the String to be when loadFileInternam is invoked by Parallel::For, since you haven't supplied any context.

But the type of Action that might suit your needs is: Action<Int32>.
This Action will be passed an Int32 from the range you passed to Parallel::For, i.e. 1..16 (not inclusive).
You can use this index to select the relevant string to pass to loadFileInternam.

Something like:

ref class Form1
{
    // The actual method you need to invoke:
    void loadFileInternam(String ^ fn)
    {
    }

    // The Action used by Parallel::For (will be called for [1,16) in this case):
    void loadFileInternamHelper(Int32 idx)
    {
        String^ s = "aaa";  // determine s according to idx
        loadFileInternam(s);
    }

    void Run()
    {
        Action<Int32>^ act = gcnew Action<Int32>(this, &Form1::loadFileInternamHelper);
        System::Threading::Tasks::Parallel::For(1, 16, act);
    }
};