【问题标题】:Start a task with Action with multiple template args使用具有多个模板参数的 Action 启动任务
【发布时间】:2012-11-15 10:56:47
【问题描述】:

我需要在 C# 中启动一个任务,所以我正在创建一个动作对象。

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

但是,当我尝试从中创建任务时,我意识到 new Task 只能接受 ActionAction&lt;object&gt; 并且拒绝接受我的 action 及其多个模板化参数。

你有什么想法可以创建这个任务对象并让我传递参数吗?

【问题讨论】:

    标签: c# multithreading templates task


    【解决方案1】:

    只需使用 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));
    

    如果您考虑一下,您不能将Action&lt;int, int, int&gt; 交给Task.Run,因为您还必须提供参数。 Task.Run 不知道你想传入什么。

    【讨论】:

      【解决方案2】:

      如何为您的参数创建一个类作为 DTO?

      
      public class ParamDto
      {
         public string Param1;
         .
         .
         .
      }
      

      【讨论】:

      • 我想尽量避免这种情况。
      • 那么你为什么要这样做?此时您有一个灵活的界面。如果需要添加或删除参数,则只需要修改类和方法。其余部分保持不变。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-21
      • 2019-02-25
      • 2021-01-29
      • 1970-01-01
      • 1970-01-01
      • 2012-12-26
      相关资源
      最近更新 更多