将整数传递给 gcnew 任务 vc++ .net 中的函数 运行
Pass an integer to a function running in a gcnew task vc++ .net
我想将一个增量整数传递给一个函数,该函数将在 .NET C++ 的不同任务中 运行。
Public: void loop()
{
int i=0;max=100;
while(i<max){
Task ^newtask= gcnew Task (gcnew Action(&mainform::dosomething),cancellationtoken);
i++;
}
}
Public: Void dosomething(int j)
{
}
这里我想将整数 i
传递给函数 dosomething
,它将成为新任务的方法。
请帮助我解决将参数传递给 c++ 中的任务的问题。
您可以使用带有 Action<Object>
参数的 Task
constructor 版本,这样您就可以将所需的输入参数(包括取消标记)传递给由任务。
示例:
ref class Test
{
public:
void Loop()
{
auto tokenSource = gcnew CancellationTokenSource();
auto token = tokenSource->Token;
int i = 0, max = 100;
while (i < max)
{
auto tuple = gcnew tuple_t(i, token);
auto newtask = gcnew Task(gcnew Action<Object^>(this, &Test::DoSomething), tuple, token);
newtask->Start();
i++;
}
}
void DoSomething(Object^ state)
{
auto tuple = static_cast<tuple_t^>(state);
int data = tuple->Item1;
CancellationToken token = tuple->Item2;
// ...
}
private:
typedef Tuple<int, CancellationToken> tuple_t;
};
谢谢塞巴科特。你帮我解决了这个问题。我可以将整数作为参数传递给任务。
我想将一个增量整数传递给一个函数,该函数将在 .NET C++ 的不同任务中 运行。
Public: void loop()
{
int i=0;max=100;
while(i<max){
Task ^newtask= gcnew Task (gcnew Action(&mainform::dosomething),cancellationtoken);
i++;
}
}
Public: Void dosomething(int j)
{
}
这里我想将整数 i
传递给函数 dosomething
,它将成为新任务的方法。
请帮助我解决将参数传递给 c++ 中的任务的问题。
您可以使用带有 Action<Object>
参数的 Task
constructor 版本,这样您就可以将所需的输入参数(包括取消标记)传递给由任务。
示例:
ref class Test
{
public:
void Loop()
{
auto tokenSource = gcnew CancellationTokenSource();
auto token = tokenSource->Token;
int i = 0, max = 100;
while (i < max)
{
auto tuple = gcnew tuple_t(i, token);
auto newtask = gcnew Task(gcnew Action<Object^>(this, &Test::DoSomething), tuple, token);
newtask->Start();
i++;
}
}
void DoSomething(Object^ state)
{
auto tuple = static_cast<tuple_t^>(state);
int data = tuple->Item1;
CancellationToken token = tuple->Item2;
// ...
}
private:
typedef Tuple<int, CancellationToken> tuple_t;
};
谢谢塞巴科特。你帮我解决了这个问题。我可以将整数作为参数传递给任务。