Reputation: 165
I have the following code in .Net C# that makes a call, and then evaluates the response. If the response is Pending, I want to wait 2 seconds, and make the call again.
I do not know how to do the "Wait 2 seconds" here, or how to use a timer that works with the synchronous method.
I am limited by the constraints of a PCL project.
private async Task<Response> ExecuteTask(Request request)
{
var response = await GetResponse();
switch(response.Status)
{
case ResponseStatus.Pending:
//wait 2 seconds
response = await ExecuteTask(request);
}
return response;
}
Would the following code be ok?
System.Threading.Timer timer;
private async Task<Response> ExecuteTask(Request request)
{
var response = await GetResponse();
switch(response.Status)
{
case ResponseStatus.Pending:
timer = new System.Threading.Timer(async obj =>
{
response = await ExecuteTask(request);
}, null, 1000, System.Threading.Timeout.Infinite);
}
return response;
}
Upvotes: 1
Views: 3485
Reputation: 116558
In async you wait using Task.Delay
private async Task<Response> ExecuteTask(Request request)
{
var response = await GetResponse();
switch(response.Status)
{
case ResponseStatus.Pending:
await Task.Delay(TimeSpan.FromSeconds(2))
response = await ExecuteTask(request);
break;
}
return response;
}
Upvotes: 1