Kuker Kuker - 4 days ago 6
C# Question

Return value after timer finishes

I have a simple application that connects to API, scans a file and checks its status. Scanning can take a period of time, and I want to 'ask' api every 5 seconds about the file status, and, if it's clean - return true, if other - return false.
The problem is that I don't know how to tell the program to wait until the condition have been met before returning value. My code looks something like this:

bool Scan(string filePath){
Scanner.Scan(filePath);
//now repeat line below every 2s until the result is positive
var result = Scanner.CheckStatus();
// I dont want to go below before status is positive or x seconds has elapsed
return result
}

Answer

async/await approach looks clear enough. You can use async/await even you didn't have UI.

async Task<bool> Scan(string filePath)
{
    Scanner.Scan(filePath);
    var result = Scanner.CheckStatus();

    while(result == false)
    {
        await Task.Delay(2000);
        result = Scanner.CheckStatus();
    }

    return result
}

Because your Scanner.Scan method working with IO - it become very good candidate for asynchronous method which uses async/await.

Comments