Repeating Code While Still Triggering Events

Nathan Sokalski 4,111 Reputation points
2023-03-05T02:39:41.6233333+00:00

I have a set of code that I want to repeat continuously until I explicitly tell it to stop (basically an infinite loop). However, I also need to be able to detect events (such as clicking a button). How can I do this?

Developer technologies .NET Xamarin
Developer technologies .NET Other
Developer technologies C#
{count} votes

1 answer

Sort by: Most helpful
  1. Karen Payne MVP 35,586 Reputation points Volunteer Moderator
    2023-03-07T19:19:24.23+00:00

    Here is a conceptual example

    static bool Outcome()
    {
        // replace with your work
        return new Random().Next(0, 99) > 50;
    }
    
    // with async/await
    async Task<bool> WaitForItToWorkAsync()
    {
        var succeeded = false;
    
        while (!succeeded)
        {
            succeeded = Outcome(); // do something
            await Task.Delay(1000);
        }
        return succeeded;
    }
    
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.