本文介绍了执行 Task.Cancel 方法时抛出异常.我错过了什么吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我点击btnStart 时,循环开始并且值被添加到listBox1.我想在单击 btnPause 时暂停执行,并在单击 btnStart 时再次继续.我如何实现这一目标?请帮我.下面的代码我试过但没有运气.

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();
}

推荐答案

您可以使用 PauseTokenSource/PauseToken 组合来自 Stephen Cleary 的 Nito.AsyncEx.Coordination 包.它与 CancellationTokenSource/CancellationToken 组合的概念类似,但它不是取消,而是暂停等待令牌的工作流.

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();
}

这篇关于执行 Task.Cancel 方法时抛出异常.我错过了什么吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 07:02