title: RestSharp - Asynchronous Request Reply Pattern
body: <p>The following situation is given:</p>
  <ol>
  <li><p>A new job is sent to an API via Post Request. This API returns a JobID and the HTTP ResponseCode 202.</p>
  </li>
  <li><p>This JobID is then used to request a status endpoint. If the end point has a &quot;Finished&quot; property set in the response body, you can continue with step 3.</p>
  </li>
  <li><p>The results are queried via a result endpoint using the JobID and can be processed.</p>
  </li>
  </ol>
  <p>My question is how I can solve this elegantly and cleanly. Are there perhaps already ready-to-use libraries that implement exactly this functionality? I could not find such functionality for RestSharp or another HttpClient.
  The current solution looks like this:</p>
  <pre class="lang-cs prettyprint-override"><code>async Task&lt;string&gt; PostNewJob()
  {
    var restClient = new RestClient(&quot;https://baseUrl/&quot;);
    var restRequest = new RestRequest(&quot;jobs&quot;);        
    //add headers
             
    var response = await restClient.ExecutePostTaskAsync(restRequest);
    string jobId = JsonConvert.DeserializeObject&lt;string&gt;(response.Content);
    return jobId;
  }
  
  async Task WaitTillJobIsReady(string jobId)
  {
    string jobStatus = string.Empty;
    var request= new RestRequest(jobId) { Method = Method.GET };  
    do
    {
      if (!String.IsNullOrEmpty(jobStatus))
          Thread.Sleep(5000); //wait for next status update
  
      var response = await restClient.ExecuteGetTaskAsync(request, CancellationToken.None);
      jobStatus = JsonConvert.DeserializeObject&lt;string&gt;(response.Content);
    } while (jobStatus != &quot;finished&quot;);
  }
  
  async Task&lt;List&lt;dynamic&gt;&gt; GetJobResponse(string jobID)
  {
    var restClient = new RestClient(@&quot;Url/bulk/&quot; + jobID);
    var restRequest = new RestRequest(){Method = Method.GET};
    var response =  await restClient.ExecuteGetTaskAsync(restRequest, CancellationToken.None);
  
    dynamic downloadResponse = JsonConvert.DeserializeObject(response.Content);
    var responseResult = new List&lt;dynamic&gt;() { downloadResponse?.ToList() };
    return responseResult;
  
  }
  
  async main()
  {
  
  var jobId = await PostNewJob();
  WaitTillJobIsReady(jobID).Wait();
  var responseResult = await GetJobResponse(jobID);
  
  //handle result
  
  }
  </code></pre>
  <p>As @Paulo Morgado said, I should not use Thread.Sleep / Task Delay in production code. But in my opinion I have to use it in the method WaitTillJobIsReady() ? Otherwise I would overwhelm the API with Get Requests in the loop?</p>
  <p>What is the best practice for this type of problem?</p>