I am trying to wade through the async functionality (C# .NET) and was curious whether an async function which returns a Task (i.e. promise) is always usable in an async function ONLY. Compiler and documentation indicate this of course, but I wanted to see if I am missing something which gets around this.
For example, the ReturnRandomIntegerAsync(i) returns a Task. Note that the while loop which runs every 5 seconds is faster than the function which takes 7 seconds :
void MyFunction(){
while(true)
{
i++;
var sw = Stopwatch.StartNew();
Thread.Sleep(5000);
Task<int> j = ps.ReturnRandomIntegerAsync(i);// Call to an async
// method which has a sleep for 7 seconds (and awaits for sleep to be over))
// **OUTPUT j**.
sw.Stop();
var timespan = sw.Elapsed;
Console.WriteLine("Elapsed time : " + timespan.Seconds + "\n\n");// Time taken for this iteration.
}
}
In this example, I cannot do an await on the ps.ReturnRandomIntegerAsync(i) unless I make the MyFunction() an async one. If I don't, then j is meaningless. If I do a .Result on the ps.ReturnRandomIntegerAsync(i), then it breaks async and the elapsed time (last line in while loop) shows 12 seconds (5 in the loop + 7 in the method).
If I want the value of j in every loop iteration ,the only solution I can think of in this scenario is to have j stored somewhere (array, collection etc.) by the async method and then retrieved later.
Would that be the correct approach ?
Taskhas been around for longer thanasyncandawait.IEnumerable<int>. Am I required toforeachthat sequence as soon as it is returned? If yes, why? If no, what are some things I could do with anIEnumerable<int>other thanforeaching it? (In case it is not clear:foreachextracts values from sequences.awaitextracts values from tasks. Logically they are the almost same thing, so if you can answer the question about sequences, you probably already know the answer about tasks.)