© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•3y ago•
16 replies
valera456

❔ What did I do wrong with this task formation?

I want to make an infinite method that generates a random number for a "slot machine". I also have to be able to stop it upon click of a button to finalize a number.
The vital code is this:
        public async Task Numbers(TextBox textbox, CancellationToken token)
        {
            Random rnd = new Random();
            while (token.IsCancellationRequested == false)
            {
                textbox.Text = rnd.Next(1, 10).ToString();
                await Task.Delay(100);
            }
        }

        public async void Check(TextBox textbox, Button button)
        {
            CancellationTokenSource cts = new CancellationTokenSource();
            if (button.Text == "Launch")
            {
                Task.Run(() => Numbers(textbox, cts.Token), cts.Token);
                button.Text = "Stop";
            }
            else if (button.Text == "Stop")
            {
                cts.Cancel();
                button.Text = "Launch";
            }
        }
        public async Task Numbers(TextBox textbox, CancellationToken token)
        {
            Random rnd = new Random();
            while (token.IsCancellationRequested == false)
            {
                textbox.Text = rnd.Next(1, 10).ToString();
                await Task.Delay(100);
            }
        }

        public async void Check(TextBox textbox, Button button)
        {
            CancellationTokenSource cts = new CancellationTokenSource();
            if (button.Text == "Launch")
            {
                Task.Run(() => Numbers(textbox, cts.Token), cts.Token);
                button.Text = "Stop";
            }
            else if (button.Text == "Stop")
            {
                cts.Cancel();
                button.Text = "Launch";
            }
        }
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

✅ What did I do wrong? (fixed)
C#CC# / help
2mo ago
what is wrong with this?
C#CC# / help
4w ago
✅ I don't understand what I did wrong(list)
C#CC# / help
3y ago