将参数传递给 C++/CLI 中的任务? [英] Pass an argument to task in C++/CLI?

查看:30
本文介绍了将参数传递给 C++/CLI 中的任务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Visual Studio 2012 中有此 C# 代码.

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

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

这将执行 SwitchLaser 方法(MyClass 类的公共非静态成员)作为带有参数 bool 的任务.

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

我想在托管 C++/CLI 中做类似的事情.但是我无法找到如何运行任务的任何方法,该任务将执行一个带一个参数的成员方法.

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));
}

SwitchLaserHelper 函数的实现:

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

必须有一些像 C# 一样的解决方案,而不是创建辅助函数和成员(这不是线程安全的).

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

推荐答案

目前还没有任何方法可以做到这一点.

There isn't yet any way to do this.

在 C# 中,您有一个闭包.在编写 C++/CLI 编译器时,仍在讨论 C++ 中闭包的标准化语法.值得庆幸的是,微软选择等待并使用标准的 lambda 语法,而不是引入另一种独特的语法.不幸的是,这意味着该功能尚不可用.当它是时,它看起来像:

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:

gcnew Action([this, on](){ SwitchLaser(on) });

当前的线程安全解决方案是做 C# 编译器所做的事情——将辅助函数和数据成员放入嵌套的子类型中,而不是放入当前类中.当然,除了本地变量之外,您还需要保存 this 指针.

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.

ref class MyClass::SwitchLaserHelper
{
    bool laserOn;
    MyClass^ owner;

public:
    SwitchLaserHelper(MyClass^ realThis, bool on) : owner(realThis), laserOn(on) {}
    void DoIt() { owner->SwitchLaser(laserOn); }
};

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

C++ lamdba 语法将简单地为您创建该辅助类(目前它适用于本机 lambda,但不适用于托管的).

The C++ lamdba syntax will simply create that helper class for you (currently it works for native lambdas, but not yet for managed ones).

这篇关于将参数传递给 C++/CLI 中的任务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆