I understand that a Stopwatch can be useful to keep iterating a loop until X amount of time has elapsed:
void DoWork()
{
TimeSpan maxDuration = TimeSpan.FromMinutes(3);
Stopwatch sw = Stopwatch.StartNew();
while (sw.Elapsed < maxDuration)
{
// do some work
}
}
But what if that loop contains an action (such as a call to an external resource) which takes a long time, won't the loop wait until the response has returned, before iterating again and seeing that the StopWatch has elapsed?
void DoWork()
{
TimeSpan maxDuration = TimeSpan.FromMinutes(3);
Stopwatch sw = Stopwatch.StartNew();
while (sw.Elapsed < maxDuration)
{
var response = CallExternalResourceWhichTakes5Minutes()
}
}
Am I correct in that we won't check the while loop's condition again until the response has come back? If so, what would be an appropriate solution to abort the external call if the timer elapses before a response is returned?