具有参数和返回值的Task.Factory.StartNew

尝试调用需要参数的方法以获取结果并传递结果以继续。 但我是Task领域的新手,似乎无法弄清楚正确的语法。 任何帮助,将不胜感激。

Task.Factory.StartNew(() => CheckConflict(startDate, endDate, actID, repeatRule,whichTime)) .ContinueWith( GetConflictDelegate(result), TaskScheduler.FromCurrentSynchronizationContext); 

假设您想继续使用CheckConflict()的结果, ContinueWithTask作为参数。 Task有一个属性Result ,它将是方法调用的结果。

有关示例,请参阅下面的代码段。

 new TaskFactory() .StartNew(() => { return 1; }) .ContinueWith(x => { //Prints out System.Threading.Tasks.Task`1[System.Int32] Console.WriteLine(x); //Prints out 1 Console.WriteLine(x.Result); }); 

我建议你使用async / await

 var result = await Task.Run( () => CheckConflict(startDate, endDate, actID, repeatRule, whichTime); GetConflictDelegate(result); 
 Task.Factory.StartNew(new Func(() => { return 1; }).ContinueWith(new Action((result) => { Console.Writeline(result.Result); // output: 1 }); 

试试这个

你需要Task类(参见MSDN – TaskFactory.StartNew-Methode(Func,Object) 。 是你调用方法的返回类型。因为你开始一个新线程,你必须等到线程完成没有阻塞主线程或引导messagepump停止。这是你可以使用async和await的地方。

假设一个方法Calculate()接受两个double类型的参数并返回double的结果,另一个方法叫Validate(),它validation结果。 解决方案可能如下所示:

 private async Task CalculateAsync() { // Our parameter object CustomArgsObject customParameterObject = new CustomArgsObject() { Value1 = 500, Value2 = 300 }; Task returnTaskObject = await Task.Factory.StartNew( (paramsHoldingValues) => Calculate(paramsHoldingValues as CustomArgsObject), customParameterObject); // Because of await the following lines will only be executed // after the task is completed while the caller thread still has 'focus' double result = returnTaskObject.Result; Validate(result); } private double Calculate(CustomArgsObject values) { return values.Value1 + values.Value2; } private bool Validate(double value) { return (value < 1000); } 

await将焦点返回给调用者线程(调用CalculateAsync()的线程)以防止在任务运行时锁定。 同时await强制处理CalculateAsync(),直到任务启动的行,然后等待任务完成。 然后将处理CalculateAsync()的其余部分。 在没有await的情况下,将处理整个方法 - 在任务完成之前或与运行任务同时进行。

Task类(其中是返回类型的占位符)具有属性Result ,其保存类型的返回值。

这有效:

 Task.Factory.StartNew(()=> { return CheckConflict(startDate, endDate, actID, repeatRule,whichTime); }).ContinueWith(x=> { GetConflictDelegate(whichTime); },TaskScheduler.FromCurrentSynchronizationContext());