使用具有多个模板参数的Action启动任务

Sca*_*ark 4 c# multithreading templates task

我需要在C#中启动一个Task,所以我正在创建一个action对象.

private Action<int, int, int> action = (int p1, int p2, int p3) =>
{
    // do some stuff with p1, p2 and p3.
};
Run Code Online (Sandbox Code Playgroud)

然而,当我尝试从它创建一个任务,我认识到,new Task只能采取ActionAction<object>并拒绝接受我action与它的多个模板参数.

您是否有任何想法如何创建此任务对象并让我传递args?

usr*_*usr 5

只需使用lambda转换为正确的委托类型:

Action<int, int, int> action = (int p1, int p2, int p3) =>
{
    // do some stuff with p1, p2 and p3.
};

//a closure can capture over any values you might want to pass in
Task.Run(() => action(1, 2, 3));
Run Code Online (Sandbox Code Playgroud)

如果你考虑一下,你就无法提供Action<int, int, int>,Task.Run因为你还必须提供参数.Task.Run 不知道你想传递什么.