Context: primitive chat bot.
I have a simple code:
private static bool busy;
private async void OnTimedEvent(object sender, ElapsedEventArgs e)
{
if (!busy)
{
busy = true;
//some logic
await SomeAsyncCommand();
busy = false;
}
else
{
await Reply("Stuff's busy yo"); // falling thru, no need to process every request
}
}
And it works fine so far, I haven't encountered any "non-atomic precision issues" with bool
yet. The issue arises when I start to do more complex stuff in async/await context, for example:
public async Task AddEntry(string url, DateTime time, User user)
{
UpdateUser(user);
// We cant fall thru here, all sent requests MUST be processed so we wait
while (busy)
{
await Task.Delay(100); // checking every 100ms if we can enter
}
busy = true;
// working with NON-CONCURRENT collection
// can await as well
busy = false;
}
My understanding is - as these threads pile up waiting for the "boolean lock" to be released, there could be a case when two of them will enter at the same time which is kill.
I know I cant use lock in the await/async context (and I also read somewhere here that CLR lock is a bad practice in async/await env in general?) and I know that bool isnt good alternative as well.
How are these situations usually handled?