valera456
valera456
CC#
Created by valera456 on 6/19/2023 in #help
❔ 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";
}
}
17 replies