developer
developer

Reputation: 377

How to use GetAsync or PostAsync in RestSharp

I can't find any examples of using GetAsync or PostAsync methods. I'm try to implement it with:

private static Task<IRestResponse> GetResultAsync(RestClient client, RestRequest request)
{
    var taskSource = new TaskCompletionSource<IRestResponse>();
    client.GetAsync(request, response =>
    {
        taskSource.SetResult(response);
    });
    return taskSource.Task;
}

and I get an error, because I don't know what must be passed as RestRequestAsyncHandle argument:

Delegate 'Action < IRestResponse, RestRequestAsyncHandle>' does not take 1 arguments

Can somebody tell me what should be passed as RestRequestAsyncHandle?

Upvotes: 0

Views: 12362

Answers (2)

Fildor
Fildor

Reputation: 16104

If you want to walk the Task-based async path, then do it all the way:

private static Task<IRestResponse> GetResultAsync(RestClient client, RestRequest request)
{
    return client.ExecuteGetAsync(request);
}

Kirk gave a good explanation what you missed about the AsyncHandle in your approach, so I won't repeat it here.

Looking at the code on github, they seem to actually have done "under the hood", what you tried. So I wouldn't reinvent the wheel.

Upvotes: 4

Kirk Larkin
Kirk Larkin

Reputation: 93123

I'm struggling to find anything specific in the documentation, but it looks like your problem is more that you're expecting to have to provide a RestRequestAsyncHandle. Instead, it looks like you need to "take" one in your callback. e.g:

client.GetAsync(request, (response, handle) =>
{
    taskSource.SetResult(response);
});

The code for RestRequestAsyncHandle shows that it contains an Abort function that you could call from within your handler, if needed.

I can't vouch for whether this is the correct way to use async in RestSharp, but I think this addresses your specific error. @Fildor's answer and comment below suggest a more correct approach to the async stuff as a whole.

Upvotes: 2

Related Questions