1
private async void button1_Click_1(object sender, EventArgs e)
{
    foreach (var word in GetWords())
    {
        richTextBox1.Text += (word + ' ');
        await Task.Delay(hız);

        Size textSize = TextRenderer.MeasureText(richTextBox1.Text, richTextBox1.Font,
            richTextBox1.Size, flags);

        if (textSize.Height >= (richTextBox1.Height - 40))
        {
            richTextBox1.Clear();
        }
    }  
}

This is the code that I use. It works, but I want to stop it any time and then continue from where I leave. The problem is I don't know how to stop.

Theodor Zoulias
  • 34,835
  • 7
  • 69
  • 104
bornemhu
  • 41
  • 8
  • 3
    You need a [CancellationTokenSource](https://learn.microsoft.com/dotnet/api/system.threading.cancellationtokensource?view=net-5.0) for task cancellation – Sir Rufo Aug 03 '21 at 18:25
  • 1
    You could consider using the `PauseTokenSource`/`PauseToken` mechanism from Stephen Cleary's [Nito.AsyncEx.Coordination](https://www.nuget.org/packages/Nito.AsyncEx.Coordination/) package. The token component is awaitable, and it can be paused/unpaused on demand by the source component. You can find a usage example [here](https://stackoverflow.com/questions/68221306/exception-is-thrown-when-i-execute-task-cancel-method-am-i-missing-something/68222074#68222074). – Theodor Zoulias Aug 04 '21 at 02:10

1 Answers1

1

If you want pause and continue a task, the simple way is to use a boolean like :

private volatile bool _isPaused = false;
private async void button1_Click_1(object sender, EventArgs e)
{
    foreach (var word in GetWords())
    {
        richTextBox1.Text += (word + ' ');

        do
        {
            await Task.Delay(hız);
        } while (_isPaused);

        Size textSize = TextRenderer.MeasureText(richTextBox1.Text, richTextBox1.Font, richTextBox1.Size, flags);


        if (textSize.Height >= (richTextBox1.Height - 40))
        {
            richTextBox1.Clear();
        }
    }
}

private async void pauseContinue_Click(object sender, EventArgs e)
{
    _isPaused = !_isPaused;
}

The volatile keyword is to manipulate primitive variable in thread-safe way.

vernou
  • 6,818
  • 5
  • 30
  • 58
  • thank you so much this fits perfectly with my code. Can you explain simply what we do in those new arrangements? Shouldn't we do _isPaused = false ; ? I didn't understand that ! thing :) – bornemhu Aug 03 '21 at 19:46
  • @bornemhu, It's to declare the field `_isPaused` and initialized it at false. – vernou Aug 03 '21 at 20:28
  • 1
    Actually the `volatile` keyword is redundant in this case, since all code runs on the UI thread. In Windows Forms applications the `await` does not cause thread switching. – Theodor Zoulias Aug 04 '21 at 02:01