简体   繁体   中英

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 ?

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.

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. eg:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM