2015-04-05 197 views
0

當創建一個新線程時,使用ThreadStart()如何將多個參數傳遞給該函數?C++/CLR在線程中傳遞多個參數

下面是一個例子:

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數量,只是有對象^食品),因爲ParameterizedThreadStart只需要一個對象^

+0

你傳遞參數給Thread :: Start()方法。您調用的函數必須採用單個Object ^參數。用safe_cast將它轉換回String ^。 – 2015-04-05 17:57:40

+0

@HansPassant好吧,我可以像你說的那樣讓它工作,但是我怎麼傳遞多個參數呢?此外,我不得不將ThreadStart()更改爲ParameterizedThreadStart() – Joesph 2015-04-05 18:25:14

+0

我已更新問題 – Joesph 2015-04-05 18:34:28

回答

1

像其他任何在這裏你有情況把多個值到一個對象,你要麼:

  • 創建一個包裝類或結構(該乾淨路)
  • 或使用一些預定義的一個像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)); 
} 
+0

非常感謝。這個答案效果很好。我希望C++ CLR有更好的線程支持,但我很高興你來拯救。 – Joesph 2015-04-05 20:50:47

+0

這實際上與線程無關。 .NET框架有很好的線程支持(線程,TPL,PLINQ等)。可悲的是C++/CLI不支持託管lambda表達式。 – 2015-04-05 21:14:45

+0

我明白了。在多線程中傳遞參數是相當痛苦的。很高興在C++ 11中變得更容易。 – Joesph 2015-04-05 21:23:54