1

When I click on btnStart, the loop is started and values are added to listBox1. I want to pause the execution when I click on btnPause, and again continue when click on btnStart. How do I achieve this? Please help me. Below code I have tried but no luck.

CancellationTokenSource source = new CancellationTokenSource();

private void btnStart_Click(object sender, EventArgs e)
{
    //here I want to start/continue the execution
    StartLoop();
}

private async void StartLoop()
{
    for(int i = 0; i < 999999; i++)
    {
        await Task.Delay(1000, source.Token);
        listBox1.Items.Add("Current value of i = " + i);
        listBox1.Refresh();
    }
}

private void btnPause_Click(object sender, EventArgs e)
{
    //here I want to pause/stop the execution
    source.Cancel();
}
Theodor Zoulias
  • 34,835
  • 7
  • 69
  • 104
hallojatin
  • 21
  • 4

1 Answers1

2

You could use the PauseTokenSource/PauseToken combo from Stephen Cleary's Nito.AsyncEx.Coordination package. It is a similar concept with the CancellationTokenSource/CancellationToken combo, but instead of canceling, it pauses the workflow that awaits the token.

PauseTokenSource _pauseSource;
CancellationTokenSource _cancelSource;
Task _loopTask;

private async void btnStart_Click(object sender, EventArgs e)
{
    if (_loopTask == null)
    {
        _pauseSource = new PauseTokenSource() { IsPaused = false };
        _cancelSource = new CancellationTokenSource();
        _loopTask = StartLoop();

        try { await _loopTask; } // Propagate possible exception
        catch (OperationCanceledException) { } // Ignore cancellation error
        finally { _loopTask = null; }
    }
    else
    {
        _pauseSource.IsPaused = false;
    }
}

private async Task StartLoop()
{
    for (int i = 0; i < 999999; i++)
    {
        await Task.Delay(1000, _cancelSource.Token);
        await _pauseSource.Token.WaitWhilePausedAsync(_cancelSource.Token);
        listBox1.Items.Add("Current value of i = " + i);
        listBox1.Refresh();
    }
}

private void btnPause_Click(object sender, EventArgs e)
{
    _pauseSource.IsPaused = true;
}

private async void btnStop_Click(object sender, EventArgs e)
{
    _cancelSource.Cancel();
}
Theodor Zoulias
  • 34,835
  • 7
  • 69
  • 104