Search code examples
c#winformsasync-awaittaskdelay

How to stop an await Task?


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.


Solution

  • 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.