C ++ / CLR在线程中传递多个参数

时间:2015-04-05 17:35:39

标签: multithreading c++-cli

当一个人创建一个新线程时,使用ThreadStart()如何将多个参数传递给该函数?

以下是一个例子:

using namespace System;
using namespace System::Threading;

public ref class Animal
{
public:
    void Hungry(Object^ food, int quantity);
};

void Animal::Hungry(Object^ food, int quantity)
{
    Console::WriteLine("The animal eats " + quantity.ToString() + food);
}

void main()
{
    Animal^ test = gcnew Animal;
    Thread^ threads = gcnew Thread(gcnew ParameterizedThreadStart(test, &Animal::Hungry)); 

    threads->Start("Grass", 1); //need to pass 2nd argument! 
}

只用一个参数就可以正常工作(如果我删除了int数量并且只有Object ^ food),因为ParameterizedThreadStart只接受一个Object ^

1 个答案:

答案 0 :(得分:1)

在任何其他需要将多个值放入一个对象的情况下,您可以:

  • 创建一个包装类或结构( clean 方式)
  • 或使用某些预定义的内容,例如Tuple lazy 方式)

这是懒惰的方式:

void Animal::Hungry(Object^ param)
{
    auto args = safe_cast<Tuple<String^, int>^>(param);
    Console::WriteLine("The animal eats {1} {0}", args->Item1, args->Item2);
}

void main()
{
    Animal^ test = gcnew Animal;
    Thread^ threads = gcnew Thread(gcnew ParameterizedThreadStart(test, &Animal::Hungry));
    threads->Start(Tuple::Create("Grass", 1));
}