这很有效:
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));
答案 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)
实际上,更清晰的方法是在对象内部传递参数。 您可以在下面找到轻松实现此目标的解决方案。
只需创建一个包含参数的类:
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
});
可以在您不想创建课程的情况下使用
修改将对象强制转换为元组的方法:
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));
修改方法以接受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 });