Home > Mobile >  C# async - creating a task properly
C# async - creating a task properly

Time:07-13

I'm creating a Task in C# but I'm not sure what I do is correct. I'm using Restsharp and in Restsharp there are two methods: Execute and ExecuteAsync. I want to do an Async call but I also need to return data to the client without blocking the execution. Therefor I created a task which will use Execute instead of ExecuteAsync. The reason why is because I have to wait until I get a response back and then return it in the right datastructure. So I thought there is no use in using ExecuteAsync if I have to await it in a Task...

My code looks as follows:

        public Task<Response> ExecuteAsync()
        {
        return new Task<Response>(() =>
        {
            var client = new RestClient(URL);

            if (_useBasicAuth)
            {
                client.Authenticator = new HttpBasicAuthenticator(_username, _password);
            }

            var request = RequestBuilder(_method);
            var response = client.Execute(request);

            return new Response()
            {
                HttpStatusCode = response.StatusCode,
                HttpStatusDescription = response.StatusDescription,
                Content = response.Content,
                Cookies = ExtractCookies(response.Cookies),
                Headers = ExtractHeaders(response.Headers)
            };
        });
    }

Is this correct? The client should be able to call ExecuteAsync without blocking the execution...

Thanks in advance! Ps Tips or best practises are more then welcome! :-)

CodePudding user response:

I strongly suspect you should really just use ExecuteAsync and write an async method:

public async Task<Response> ExecuteAsync()
{
    var client = new RestClient(URL);
    if (_useBasicAuth)
    {
        client.Authenticator = new HttpBasicAuthenticator(_username, _password);
    }

    var request = RequestBuilder(_method);
    var response = await client.ExecuteAsync(request).ConfigureAwait(false);

    return new Response
    {
        HttpStatusCode = response.StatusCode,
        HttpStatusDescription = response.StatusDescription,
        Content = response.Content,
        Cookies = ExtractCookies(response.Cookies),
        Headers = ExtractHeaders(response.Headers)
    };
}
  • Related