【问题标题】:Exception is thrown when I execute Task.Cancel method. Am I missing something? [duplicate]执行 Task.Cancel 方法时引发异常。我错过了什么吗? [复制]
【发布时间】:2021-09-14 04:17:48
【问题描述】:

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

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

【问题讨论】:

  • 你有什么问题?
  • 抛出异常什么异常?

标签: c# multithreading task


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2021-11-11
    • 2018-09-16
    • 2019-07-06
    • 2017-05-22
    • 2016-12-29
    • 1970-01-01
    • 2010-09-15
    • 2018-01-02
    相关资源
    最近更新 更多