Task.Factory.StartNew with parameters and return values

An attempt to call a method that requires parameters to get the result and pass the result to continue. But I am new to the field of tasks and, it seems, I can not understand the correct syntax. Any help would be appreciated.

Task.Factory.StartNew(() => 
    CheckConflict(startDate, endDate, actID, repeatRule,whichTime))
    .ContinueWith(
        GetConflictDelegate(result),
        TaskScheduler.FromCurrentSynchronizationContext);
+4
source share
5 answers

Assuming you want to continue the result CheckConflict(), ContinueWithtakes Task<T>as an argument. Task<T>has a property Resultthat will be the result of a method call.

See the code snippet below.

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);
    });
+3
source

I recommend using async/ await:

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

0

Task<TResult> (. MSDN - TaskFactory.StartNew-Methode (Func, Object). <TResult> - . , , , . async .

Calculate(), double double, Validate(), . :

private async Task CalculateAsync()
{
    // Our parameter object
    CustomArgsObject customParameterObject = new CustomArgsObject() 
    {
        Value1 = 500,
        Value2 = 300
    };

    Task<double> returnTaskObject = await Task<double>.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<TResult> ( <TResult> ) Result, <TResult>.

0

:

Task.Factory.StartNew(()=>
                {
                    return CheckConflict(startDate, endDate, actID, repeatRule,whichTime);

                }).ContinueWith(x=>
                    {
                        GetConflictDelegate(whichTime);
                    },TaskScheduler.FromCurrentSynchronizationContext());
0

Source: https://habr.com/ru/post/1530906/


All Articles