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

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

问题描述

我有这样的code为C#在Visual Studio 2012。

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

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

这将执行 SwitchLaser 与变量bool上的任务的方法(类 MyClass的的公共非静态成员)

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([on](){ SwitchLaserHelper(on) });

目前的线程解决方案是做什么的C#编译器 - 把辅助函数和数据成员没有到当前的类,但到嵌套子类型。当然,你需要保存这个除了局部变量的指针。

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只会为你创建的helper类(目前适用于本地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天全站免登陆