Search code examples
c++-cliargumentsactiontask

Pass an argument to task in C++/CLI?


I have this code for the C# in Visual Studio 2012.

public Task SwitchLaserAsync(bool on)
{
   return Task.Run(new Action(() => SwitchLaser(on)));
}

This will execute SwitchLaser method (public nonstatic member of a class MyClass) as a task with argument bool on.

I would like to do something similar in managed C++/CLI. But I am not able to find out any way how to run a task, which will execute a member method taking one parameter.

Current solution is like this:

Task^ MyClass::SwitchLaserAsync( bool on )
{
    laserOn = on;   //member bool 
    return Task::Run(gcnew Action(this, &MyClass::SwitchLaserHelper));
}

Implementation of SwitchLaserHelper function:

void MyClass::SwitchLaserHelper()
{
     SwitchLaser(laserOn);
}

There must be some solution like in C# and not to create helper functions and members (this is not threadsafe).


Solution

  • Here's the working answer.. Have tested it.. Passing an argument (int) to the action sampleFunction.

    #include "stdafx.h"
    #include "CLRSamples.h"
    
    using namespace System;
    using namespace System::Threading;
    using namespace System::Threading::Tasks;
    using namespace System::Collections;
    using namespace System::Collections::Generic;
    
    void CLRSamples::sampleFunction(Object^ number)
    {
        Console::WriteLine(number->ToString());
        Thread::Sleep((int)number * 100);
    }
    
    void CLRSamples::testTasks()
    {
        List<Task^>^ tasks = gcnew List<Task^>();
    
        for (int i = 0; i < 10; i++)
        {
            tasks->Add(Task::Factory->StartNew((Action<Object^>^)(gcnew Action<Object^>(this, &CLRSamples::sampleFunction)), i));
        }
    
        Task::WaitAll(tasks->ToArray());
    
        Console::WriteLine("Completed...");
    }
    
    int main(array<System::String ^> ^args)
    {
        CLRSamples^ samples = gcnew CLRSamples();
        samples->testTasks();
    
        Console::Read();
        return 0;
    }