BR75
BR75

Reputation: 667

Difference between these two async functions

Hello I dont get the difference between the following two asnyc functions, could someone explain it to me? Both of them doesnt return IRestResponse, so I cant access StatusCode field. Do I have to cast here?

public async Task<IRestResponse> Post<T>(string Ressource, T ObjTOPost) where T : new()
{
    return await Task.Factory.StartNew(() =>
    {
        var client = new RestClient("test.com");
        var request = new RestRequest(Ressource, Method.POST);

        var response = client.Execute(request);

        return response;
    });
}

And this:

public async Task<IRestResponse> Post<T>(string Ressource, T ObjTOPost) where T : new()
{
    var client = new RestClient("test.com");

    var request = new RestRequest(Ressource, Method.POST);

    var response = await client.ExecuteTaskAsync<T>(request);

    return response;
}

Upvotes: 1

Views: 115

Answers (1)

John Wu
John Wu

Reputation: 52280

Both of them doesnt return IRestResponse, so I cant access StatusCode field.

They return a Task<IRestResponse>. You can get the interface by awaiting the task, e.g.

var task = Post(resource, objectToPost);
IRestResponse response = await task;

Or in one line (more common):

var response = await Post(resource, objectToPost);

Difference between these two async functions

The second example is far more straightforward. The first example spins up an additional task and passes its awaitable back to the caller, whereas the second example awaits the RestClient directly. I see no reason to use the structure in the first example.

Upvotes: 6

Related Questions