Skip to main content

Sometimes, you need to get a return value from a Task, opposed to letting it run in the background and forgetting about it. You'll need to specify the return type as a type parameter to the Task object: a Task of T.

//
// .NET 4.0
// Without specifying an input parameter:
// ---------------------------------------------------------------------------

Task<int> task = new Task<int>(() =>
{
    int total = 0;
    for (int i = 0; i < 500; i++)
    {
        total += i;
    }
    return total;
});

task.Start();
int result = Convert.ToInt32(task.Result);

// We count to 500 and return the sum. The return value of the Task can be
// retrieved using the Result property which can be converted to the desired
// type. You can provide an input parameter as well:

Task<int> task = new Task<int>(obj =>
{
    int total = 0;
    int max = (int)obj;
    for (int i = 0; i < max; i++)
    {
        total += i;
    }
    return total;
}, 300);

task.Start();
int result = Convert.ToInt32(task.Result);

// We specify that we want to count to 300.

//
// .NET 4.5
// ---------------------------------------------------------------------------
//
// The recommended way in .NET 4.5 is to use Task.FromResult, Task.Run or
// Task.Factory.StartNew:

// FromResult:

public async Task DoWork()
{
       int res = await Task.FromResult<int>(GetSum(4, 5));
}

private int GetSum(int a, int b)
{
    return a + b;
}

//
// Please check out Stefan's comments on the usage of FromResult in the comments
// section below the post.
//
// ... Stefan Ossendorf says:
//
// Hi Andras,
// nice article! But there is one flaw.
// Task.FromResult() is NOT async! It's just a wrapper to get a Task with Status "RanToCompletion".
// Your calling Thread will block until your operation is completed.
//
// Another way to get a (running) Task is the TaskCompletionSource (see: https://msdn.microsoft.com/en-us/library/dd449174(v=vs.110).aspx)
// With a TaskCompletionSource you have more control over the tasks state Exception,Finished,Cancelled.

// Task.Run:

public async Task DoWork()
{
    Func<int> function = new Func<int>(() => GetSum(4, 5));
    int res = await Task.Run<int>(function);
}

private int GetSum(int a, int b)
{
    return a + b;
}

// Task.Factory.StartNew:

public async Task DoWork()
{
    Func<int> function = new Func<int>(() => GetSum(4, 5));
    int res = await Task.Factory.StartNew<int>(function);
}

private int GetSum(int a, int b)
{
    return a + b;
}