Jim Sweeney
Jim Sweeney

Reputation: 33

How to have a method return a started Task without blocking?

In my C# app, I've been able to start concurrent tasks that make http calls and then wait for all of them to complete.

var responseTasks = new List<Task<HttpResponseMessage>>();

// PostChanges makes an async http call and returns the task
responseTasks.Add(myServiceClient.PostChanges(json));
responseTasks.Add(myServiceClient.PostChanges(json));
responseTasks.Add(myServiceClient.PostChanges(json));

Task.WaitAll(responseTasks.ToArray());

But what if each of the calls to PostChanges relies on a call that gets data from an http request? What is the simplest way to create a method that encapsulates the two calls and returns a started task? The method would have to make both requests something like this:

public Task<HttpResponseMessage> GetDataAndPostChanges(MyInput input)
{
    var json = myServiceClient.GetData(input); // this call must complete first
    var response = myServiceClient.PostChanges(json);
    return response; // how to actually return a task immediately that does both calls?
}

I would then want to make concurrent calls to that method and wait for all of them to complete.

var responseTasks = new List<Task<HttpResponseMessage>>();

// PostChanges makes an async http call and returns the task
responseTasks.Add(myServiceClient.GetDataAndPostChanges(input1));
responseTasks.Add(myServiceClient.GetDataAndPostChanges(input2));
responseTasks.Add(myServiceClient.GetDataAndPostChanges(input3));

Task.WaitAll(responseTasks.ToArray());

Upvotes: 1

Views: 48

Answers (1)

Nkosi
Nkosi

Reputation: 247133

Make the function async and await the necessary calls

public async Task<HttpResponseMessage> GetDataAndPostChanges(MyInput input) {
    var json = await myServiceClient.GetData(input); // this call must complete first
    var response = await myServiceClient.PostChanges(json);
    return response;
}

The assumption above is that GetData is an asynchronous function.

Upvotes: 3

Related Questions