C# 任务。使用输入参数和输出运行
这非常有效:C# 任务。使用输入参数和输出运行,c#,task,task-parallel-library,C#,Task,Task Parallel Library,这非常有效: private void MainMethod() { Task<bool> taskItemFound = new Task<bool>(ItemFound); } private bool ItemFound() { //Do Work return true; } private void main方法() { Task taskItemFound=新任务(ItemFound); } 私有bool ItemFound() {
private void MainMethod()
{
Task<bool> taskItemFound = new Task<bool>(ItemFound);
}
private bool ItemFound()
{
//Do Work
return true;
}
private void main方法()
{
Task taskItemFound=新任务(ItemFound);
}
私有bool ItemFound()
{
//工作
返回true;
}
这可以工作,但很难看,我不能传递多个参数:
private void MainMethod()
{
var startNew = Task<bool>.Factory.StartNew(TempMethod, "cow");
}
private bool TempMethod(object o)
{
return ("holy " + o == "holy cow");
}
private void main方法()
{
var startNew=Task.Factory.startNew(TempMethod,“cow”);
}
私有bool-tempo方法(对象)
{
返回(“神圣的”+o==“神圣的奶牛”);
}
我正在寻找一种解决方案,它将从一个现有方法中获得一个任务
,该方法具有多个输入参数,并返回bool。理想情况下,它将如下所示:
Task<bool> taskItemFound = new Task<bool>(ItemFound(param1, param2, param3));
Task taskItemFound=新任务(ItemFound(param1,param2,param3));
您可以执行以下操作:
bool result = await Task.Run(() => ItemFound(param1, param2, param3) );
或者,如果您真的希望将其作为任务
:
Task t=新任务(()=>ItemFound(param1,param2,param3));
实际上,一种更清晰的方法是在对象内部传递参数。
在下面,您可以找到轻松实现这一目标的解决方案
解决方案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
});
然后使用以下命令调用:
Task<bool> taskItemFound = new Task<bool>(TempMethod, new {Param1 = 3, Param2 = 44, Param3 = 564 });
Task taskItemFound=new Task(TempMethod,new{Param1=3,Param2=44,Param3=564});
是,但值得注意的是,param1、param2等现在已被捕获(关闭)。它们的处理方式与原始的对象非常不同o
这会导致任何副作用吗?如何区别对待它们?是的,它们是共享的,它们的范围和寿命很难控制,甚至难以衡量。但我现在也很好奇@GregaMohorko它们有什么不同,我应该注意哪些副作用?我不知道,问问@Henkholtman,我一直在使用Task。像这样运行4年多了,我从来没有注意到任何关于对象被不同对待的事情。
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));
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 });