【问题标题】:How to define Task with parameters and return value in c++\cli?如何在 c++\cli 中定义带参数和返回值的任务?
【发布时间】:2014-08-03 15:04:55
【问题描述】:

我在 cs 文件中有一个类:

public class ThreadData
{
    private int index;

    public ThreadData(int index)
    {
        this.index = index;
    }

    public static ThreadDataOutput DoWork(ThreadDataInput input)
    {
        return new ThreadDataOutput();
    }
}

现在,我有 C++ 代码,它试图初始化一个新任务并为我们提供上述功能:

    int numOfThread = 2;
    array<Task^>^ taskArr = gcnew array<Task^>(numOfThread);
    for (int i = 0; i < numOfThread; i++)
    {
        ThreadData^ td = gcnew ThreadData(i);
        ThreadDataInput^ input = gcnew ThreadDataInput(i);
        Task<ThreadDataOutput^>^ task = gcnew Task<ThreadDataOutput^>(td->DoWork, input);
        taskArr[i] = task;
        taskArr[i]->Start();
    }

    Task::WaitAll(taskArr, 300 * 1000);

以下代码在编译时返回 2 个错误:

  1. 除非创建委托实例,否则无法获取 'ThreadData::DoWork' 的地址
  2. 无法将参数 1 从 'AmadeusWS::ThreadDataOutput ^(__clrcall *)(AmadeusWS::ThreadDataInput ^)' 转换为 'System::Func ^

我也尝试在 cs 文件中声明这样的委托:

    public static Func<ThreadDataInput, ThreadDataOutput> DoWork2 = delegate(ThreadDataInput taskDataInput)
    {
        return new ThreadDataOutput();
    };

但我不知道如何从 c++\cli 代码中调用它

谁能帮助我理解如何定义可以接受参数的 cli 委托?

谢谢

【问题讨论】:

    标签: multithreading delegates c++-cli task


    【解决方案1】:

    为了在 C++/CLI 中创建一个委托实例,您需要显式地构造它,并指定将调用它的对象与要调用的类和方法分开。

    gcnew Func<TInput, TOutput>(theObject, &TheClass::MethodToInvoke)
    

    请注意,要调用的方法是以 C++ 样式指定的。

    将其替换为您的任务创建,我相信这句话对您有用:

    Task<ThreadDataOutput^>^ task = gcnew Task<ThreadDataOutput^>(
        gcnew Func<ThreadDataInput^, ThreadDataOutput^>(td, &ThreadData::DoWork), 
        input);
    

    编辑

    在您在评论中发布的代码中,您错过了调用委托的对象。

    gcnew Func<Object^, Object^>(td, &ThreadData::DoWork)
                                 ^^
    

    【讨论】:

    • 嗨。 thx for the answear 但这段代码没有编译 编译的是这样的: task = gcnew Task( gcnew Func(&ThreadData::DoWork), input);
    • 此代码仅在 DoWork 不是静态的情况下才会编译。但就我而言,它是,所以不需要 td 对象。
    • 啊。因为您的原始代码试图使用td-&gt;DoWork 作为委托,所以我认为静态是为了让它编译的实验性尝试,而不是它的设计方式。我的错。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-01
    • 2016-01-24
    • 2019-11-20
    相关资源
    最近更新 更多