I have an application that runs a task which checks for a file in a directory and completes when a file has been added to the directory. Here's a simplified example:
Private Async Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim addedFile = Await Task.Factory.StartNew(New Func(Of FileInfo)(
Function()
Dim di = New DirectoryInfo("C:\_Temporary\Test")
Do While True
Dim files = di.GetFiles()
If (files.Count > 0) Then
Return files(0)
End If
Loop
End Function))
MsgBox(addedFile.FullName)
End Sub
I've left out superfluous details like cancellation tokens, etc.
The issue is that the CPU is holding steady around 12% when the code is running. Even if I comment out the body inside the while loop, it remains the same.
How can I create a looping mechanism, which is required for non-awaitable operations like waiting for a file to arrive in a directory, without using that much CPU?
Note: The question is not about the concrete case involving the file system; it's looping non-awaitable operations in general and the effect on the CPU.
The Windows event message loop, by contrast, takes up less than 1% -- e.g. if I look at the CPU usage of my app before I click "Button1" which runs the above code.