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

C++/CLR Passing multiple arguments in threads

创建新线程时,使用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 quantity 并且只有 Object^food),因为 ParameterizedThreadStart 只需要一个 Object^

与您必须将多个值放入一个对象的任何其他情况一样,您可以:

  • 创建包装器 class 或结构(clean 方式)
  • 或使用一些预定义的方式,例如 Tuple惰性 方式)

这是懒惰的方法:

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