For example, consider:
public class Student
{
public async Task Run()
{
var rand = new Random();
while (true)
{
await ReadBook();
await Task.Delay(rand.Next(4000));
}
}
public async Task ReadBook()
{
// ...
}
}
class Main
{
async Task Run()
{
var s1 = new Student();
var s2 = new Student();
s1.Run();
s2.Run();
while (true)
{
Console.WriteLine("Books read: {0}", GetReadBooks());
await Task.Delay(10000);
}
}
int GetReadBooks()
{
return 1;
}
}
Do I need to await Student.Run()
, or even maintain a reference to the returned task at all? I understand the need if I ever want to cancel the task; I suspect I also need to await this in order to receive any exceptions thrown by Student.Run()
, but beyond that, do I care about these tasks?
Can two students read books at the same time?
Leaving out the await
would mean s2.Run()
starts when s1.Run()
is in progress. In this case, you want s1.Run()
and s2.Run()
to run concurrently, so you definitely should not simply write await s1.Run();
. Since your loops are never-ending, awaiting them doesn't make too much sense except for exceptions, but I would be surprised if your loops are truly never-ending in your real code. Task
is intended to represent something that finishes at some point. And if you can tell when that finishes, then you can determine based on that what the appropriate place to await
the task is.
I would probably guess that saving the tasks in variables, and putting await Task.WhenAll(run1, run2);
somewhere after, would be the most appropriate, but depending on your real code, it might not be suitable for you.