What is the proper way to chain Tasks when returning a Task?

Viewed 26097

I am so so with using Tasks in C# but I get confused when I try to return a Task from a method and that method will do multiple tasks within itself. So do I have my method spin up a new Task and then do everything sequentially inside of there? It's hard to wrap my head around doing it all with .ContinueWith()

Example:

public Task<string> GetSomeData(CancellationToken token)
{
    return Task.Factory.StartNew(() =>
    {
        token.ThrowIfCancellationRequested();

        var initialData = GetSomeInteger(token).Result;

        return GetSomeString(initialData, token).Result;
    });
}

public Task<int> GetSomeInteger(CancellationToken token)
{
    return Task<int>.Factory.StartNew(() =>
    {
        return 4;
    }, token);
}

public Task<string> GetSomeString(int value, CancellationToken token)
{
    return Task<string>.Factory.StartNew(() =>
    {
        return value.ToString();
    }, token);
}

I am unsure how else to write this method to make it use Tasks correctly. I guess I just feel like there should be a .ContinueWith in there or something.

Possible fix??

public Task<string> GetSomeData(CancellationToken token)
{
    return GetSomeInteger(token).ContinueWith((prevTask) =>
    {
        return GetSomeString(prevTask.Result, token);
    }, token).Unwrap();
}
3 Answers
Related