I have a WinForms app and in that app I have a repository class, Collections, that makes calls to a restful service using RestSharp. The repository code is similar to this...
public Task<IRestResponse<List<CollectionDto>>> GetCollectionsPagedAsync()
{
var client = RestClientFactory.Create();
var request = new RestRequest("api/collections");
// Parameters omitted for brevity
return client.ExecuteTaskAsync<List<CollectionDto>>(request);
}
What I thought would happen is that this would kick off the service operation and immediately return a task. Then, while the service operation was working the front end would be free to perform other operations. After those were finished it would await
the task. So the front end would be similar to...
var repository = new CollectionRepository();
var getCollectionsTask = repository.GetCollectionsPagedAsync();
// Do other initialization work here
// If the collections task hasn't completed, wait it out...
var collectionList = await getCollectionsTask;
I put a breakpoint in my service operation and tested this code. The call to ExecuteTaskAsync does not cause the breakpoint to be hit. Only when I execute the await does the operation actually start running.
I'm fairly new to async in C# but it appears that RestSharp is giving me back a "cold task." I can't call Start
on the task myself or I get "Start may not be called on a promise-style task." According to this SO thread...
You are getting that error because the Task class already started the task before giving it to you.
So I'm stumped. The absence of a breakpoint hit (and other tests) suggests I have a cold task, the error message suggests I have a hot task. So what is the correct way to consume a restful service in an async manner?