Hi,
I thought I was beginning to understand the new
async
/
await
keywords. Then I had cause to write something like the code below, similar to an extremely slow game loop, which simply runs continuously until a flag changes value. This is a much-shortened version of the code:
public static LoopFlag { get; set; } = true;
public static void MyEventHandler()
{
Task.Factory.StartNew( () => WorkerLoop() );
}
private static async void WorkerLoop()
{
do
{
Debug.WriteLine( "WorkerLoop()..." );
await Task.Delay( 1000 );
} while( LoopFlag );
}
Now, as I understand it, when the
await
keyword it encountered, control simply passes back to the caller, and a 'continuation marker' is placed in the code, a promise to come back to this point when the task has completed.
I also think I read that
Task.Delay()
creates a new
Task
that runs for the specified time before completing.
So, my question is, is the code above 'safe', or will it simply whiz round as fast as it can, creating thousands of new
Task.Delay( 1000 )
objects?
Any advice would be gratefully received.
Kind wishes ~ Patrick
What I have tried:
I've tried something similar to the code above. It seems to do exactly what I want, but I'm not sure how to tell if I am ending up with thousands of objects piling up in the background.