问题
This works great:
private void MainMethod()
{
Task<bool> taskItemFound = new Task<bool>(ItemFound);
}
private bool ItemFound()
{
//Do Work
return true;
}
This works but is UGLY and I can't pass more than one parameter:
private void MainMethod()
{
var startNew = Task<bool>.Factory.StartNew(TempMethod, "cow");
}
private bool TempMethod(object o)
{
return ("holy " + o == "holy cow");
}
I'm looking for a solution that will give me a Task<bool>
from an existing method with more than one input parameter and that returns a bool. Ideally, it would look like this:
Task<bool> taskItemFound = new Task<bool>(ItemFound(param1, param2, param3));
回答1:
You can do:
bool result = await Task.Run(() => ItemFound(param1, param2, param3) );
Or if you really want it as Task<bool>
:
Task<bool> t = new Task<bool>(() => ItemFound(param1, param2, param3) );
回答2:
Actually, a more clear way would be passing the parameters inside an object. Below you can find solutions to easily achieve that.
Solution 1 (long but clear): Pass an object which holds the parameters
Just create a class which holds the parameters:
class CustomParams
{
public int Param1 { get; set; }
public int Param2 { get; set; }
public int Param3 { get; set; }
}
Then in the method just to cast the object to the class
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");
}
And to call, use this:
Task<bool> taskItemFound = new Task<bool>(TempMethod, new CustomParams {
Param1 = 3,
Param2 = 5,
Param3 = 2
});
Solution 2 (hacky but shorter): Use Tuples as parameters
This can be used in case you don't want to create a class
Modify the method to cast the object to tuple:
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");
}
Then use:
Task<bool> taskItemFound = new Task<bool>(ItemFound, new Tuple<int, int>(3,5,7));
Solution 3 (super-hacky, and short): Use dynamic objects
Modify the method to accept dynamic
instead of object:
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");
}
And then call using this:
Task<bool> taskItemFound = new Task<bool>(TempMethod, new {Param1 = 3, Param2 = 44, Param3 = 564 });
来源:https://stackoverflow.com/questions/49587439/task-run-with-input-parameters-and-output