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?

4

3 回答 3

3

在 C++/CLI 中,您需要明确指定希望委托调用函数的对象。

ThreadPool::QueueUserWorkItem(gcnew WaitCallback(this, &CTest::testFunction));
                                                 ^^^^
于 2013-08-06T13:03:43.650 回答
1

您不应该在 .NET 中使用线程池。您应该考虑使用System::Threading::Tasks。这是使用多个“任务”的更有效方式......

还要注意 C#4.5 中新的“async”关键字。这很有帮助!因此,您应该真正考虑将应用程序的 .NET 部分放入 C#...,并且仅将 C++/CLI 用于 InterOp 场景。

于 2013-08-06T19:53:33.080 回答
1

尝试这个:

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

WaitCallback(ctest为分配的对象提供内存上下文 为CTest &CTest::testFunction));实际分配的函数内存地址提供内存转移testFunction
“动态”函数是“动态”类对象的一部分。
这一定是因为垃圾收集器。

于 2015-11-04T07:54:02.023 回答