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).
Here's the working answer.. Have tested it.. Passing an argument (int) to the action sampleFunction.
Here's generic code I wrote this afternoon which might help (although it's not an exact match for this question). Maybe this will help the next person who stumbles onto this question.
Usage is
There isn't yet any way to do this.
In C# you have a closure. When your C++/CLI compiler was written, the standardized syntax for closures in C++ was still being discussed. Thankfully, Microsoft chose to wait and use the standard lambda syntax instead of introducing yet another unique syntax. Unfortunately, it means the feature isn't yet available. When it is, it will look something like:
The current threadsafe solution is to do what the C# compiler does -- put the helper function and data members not into the current class, but into a nested subtype. Of course you'll need to save the
this
pointer in addition to your local variable.The C++ lamdba syntax will simply create that helper class for you (currently it works for native lambdas, but not yet for managed ones).
I had a similar problem when I wanted to provide a parameter to a task executing a method which does not return a value (retuns
void
). Because of thatFunc<T, TResult>
was not an option I could use. For more information, please check the page Using void return types with new Func.So I ended up with a solution where I created a helper class
which is using
Action<T>
delegate to encapsulate a method that has a single parameter and does not return a value.I would then use this helper class in a following way
Approach using the helper class is probably not the most elegant solution, but is the best one I could find to be used in C++/CLI which does not support lambda expressions.