具有输入参数和输出的Task.Run

时间:2018-03-31 11:51:51

标签: c# task task-parallel-library

这很有效:

private void MainMethod()
{
    Task<bool> taskItemFound = new Task<bool>(ItemFound);
}

private bool ItemFound()
{
    //Do Work
    return true;
}

这可行,但很难,我不能传递多个参数:

private void MainMethod()
{
    var startNew = Task<bool>.Factory.StartNew(TempMethod, "cow");
}

private bool TempMethod(object o)
{
    return ("holy " + o == "holy cow");
}

我正在寻找一个解决方案,它会从一个带有多个输入参数的现有方法中获得Task<bool>并返回一个bool。理想情况下,它看起来像这样:

Task<bool> taskItemFound = new Task<bool>(ItemFound(param1, param2, param3));

2 个答案:

答案 0 :(得分:6)

你可以这样做:

bool result = await Task.Run(() => ItemFound(param1, param2, param3) );

或者如果你真的想要Task<bool>

Task<bool> t = new Task<bool>(() => ItemFound(param1, param2, param3) );

答案 1 :(得分:1)

实际上,更清晰的方法是在对象内部传递参数。 您可以在下面找到轻松实现此目标的解决方案。

解决方案1(长而清晰):传递一个包含参数的对象

只需创建一个包含参数的类:

class CustomParams
{
   public int Param1 { get; set; }
   public int Param2 { get; set; }
   public int Param3 { get; set; }
}

然后在方法中仅将对象强制转换为类

private bool TempMethod(object arguments)
{
    var args = arguments as CustomParams;
    // Do anything with args.Param1
    // Do anything with args.Param2
    // Do anything with args.Param3
    // Return anything
    return ("holy " + args.Param1 == "holy cow");
}

要呼叫,请使用此:

Task<bool> taskItemFound = new Task<bool>(TempMethod, new CustomParams {
    Param1 = 3,
    Param2 = 5,
    Param3 = 2
});

解决方案2(hacky,但更短):使用元组作为参数

可以在您不想创建课程的情况下使用

修改将对象强制转换为元组的方法:

private bool TempMethod(object arguments)
{
    var args = arguments as Tuple<int,int,int>;
    // Do anything with args.Item1
    // Do anything with args.Item2
    // Do anything with args.Item3
    // Return anything
    return ("holy " + args.Item1 == "holy cow");
}

然后使用:

Task<bool> taskItemFound = new Task<bool>(ItemFound, new Tuple<int, int>(3,5,7));

解决方案3(超级骇客,简而言之):使用动态对象

修改方法以接受dynamic而不是对象:

private bool TempMethod(dynamic arguments)
{
    // Do anything with args.Param1
    // Do anything with args.Param2
    // Do anything with args.Param3
    // Return anything
    return ("holy " + arguments.Param1 == "holy cow");
}

然后使用此电话:

Task<bool> taskItemFound = new Task<bool>(TempMethod, new {Param1 = 3, Param2 = 44, Param3 = 564 });