Repeating Code While Still Triggering Events

Nathan Sokalski 4,126 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?

Xamarin
Xamarin
A Microsoft open-source app platform for building Android and iOS apps with .NET and C#.
5,326 questions
.NET
.NET
Microsoft Technologies based on the .NET software framework.
3,647 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,648 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Karen Payne MVP 35,386 Reputation points
    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