If you want the program to wait asynchronously for a while, consider using the Task.delay method.
For example, simulate an asynchronous operation in a unit test.
Static Async Task<t> delayedresult<t>(t result, TimeSpan delay)
{
Await Task.delay (Delay);
return result;
}
Another example, when we need to download content remotely, because the state of the remote server is not stable, if only one method is called, may not be able to obtain the desired data.
We can call the method once at a time, get the content to the remote server, for example, wait 1 seconds for the first time, wait 2 seconds for the second, wait for 4 seconds for the third time, and then try again. That is, limit access to remote content.
Static Async Task<string> downloadfromremote (String uri)
{
using (var client = new HttpClient ())
{
Wait 1 seconds first
var nextdelay = timespan.fromseconds (1);
Try 3 times to the 3rd end of the loop
for (int i = 0; I! = 3; i++)
{
Try
{
return await client. Getstringasync (URI);
}
catch (Exception ex)
{
Throw
}
Await Task.delay (Nextdelay);
Nextdelay = Nextdelay + nextdelay;
}
Finally try again
return await client. Getstringasync (URI);
}
}
Remote content can also be acquired in limited time. For example, the time limit in 3 seconds to obtain a remote resource, if not obtained within 3 seconds to return null.
Static Async Task<string> donwloadfromremote (String uri)
{
using (var client = new HttpClient ())
{
Tasks to get content from remote
var downloadtask = client. Getstringasync (URI);
3-Second Limited time task
var timeouttask = Task.delay (3000);
Get one of the 2 tasks above
var completedtask = await Task.whenany (downloadtask, Timeouttask);
If the final task waits for a limited-time task, it returns null.
if (Completedtask = = Timeouttask)
{
return null;
}
return await Downloadtask;
}
}
Reference: C # concurrent Programming classic Instances
2 application instances of the Task.delay method, unit test waits, limited time limit download remote resources