1

I'm looking for this stackoverflow: How to get Windows thread pool to call class member function? for C++/CLI: I have a ref class with a member function (a copy of that function is static for testing purposes):

ref class CTest
{
public:
  static void testFuncStatic( System::Object^ stateInfo )
  {
    // do work;
  }
  void testFunction( System::Object^ stateInfo )
  {
    // do work;
  }
};

From main() I can easily add a call to the static function to the threadpool:

System::Threading::ThreadPool::QueueUserWorkItem (gcnew System::Threading::WaitCallback (&CTest::testFuncStatic));

But I don't want to call the static function (which is more or less an object-independent global function), I want to call the member function testFunction() for several instances of the class CTest.
How can I achieve that?

Community
  • 1
  • 1
Tobias Knauss
  • 3,361
  • 1
  • 21
  • 45

3 Answers3

3

In C++/CLI, you need to explicitly specify the object you want the delegate to call the function on.

ThreadPool::QueueUserWorkItem(gcnew WaitCallback(this, &CTest::testFunction));
                                                 ^^^^
David Yaw
  • 27,383
  • 4
  • 60
  • 93
  • @ David: `this` doesn't work because in main() there is no `this`, but you've put me on the right track, Thank you!! The solution: CTest^ ctest01 = gcnew CTest; ThreadPool::QueueUserWorkItem (gcnew WaitCallback (ctest01, &CTest::testFunction)); – Tobias Knauss Aug 06 '13 at 13:19
1

You should not use thread pools in .NET. You should consider to use System::Threading::Tasks. This is an even more efficient way to use multiple "Tasks"...

Also be aware of the new "async" keyword in C#4.5. This helps a lot! So you should really consider to put the .NET part of your application into C#... and only use C++/CLI for InterOp scenarios.

Jochen Kalmbach
  • 3,549
  • 17
  • 18
  • The Task-Paralell-Library is more efficient that the "QueueUserWorkItem"... See also: http://blogs.msdn.com/b/pfxteam/archive/2009/10/06/9903475.aspx Conclusion: Task is now the preferred way to queue work to the thread pool. See also: http://stackoverflow.com/questions/16252217/is-there-a-difference-between-threadpool-queueuserworkitem-and-delegate-begininv http://stackoverflow.com/questions/9200573/threadpool-queueuserworkitem-vs-task-factory-startnew – Jochen Kalmbach Aug 07 '13 at 08:08
1

Try this:

CTest ^ ctest = gcnew CTest;
ThreadPool::QueueUserWorkItem(gcnew WaitCallback(ctest, &CTest::testFunction));
                                                 ^^^^^

WaitCallback(ctest provides memory context to allocated object of CTest &CTest::testFunction)); provides memory shift to actual allocated function memory address of testFunction.
'Dynamic' functions are part of 'dynamic' class object.
This must be like that because of garbage collector.

MrHIDEn
  • 1,723
  • 1
  • 25
  • 23