如何中止async / await以外的方法

时间:2018-05-07 07:30:18

标签: c# async-await

我有1个方法和1个事件

private void Grid_MouseWheel(object sender, MouseWheelEventArgs e)
    {
        if (currentSection == OsuSection.PreLoad)
            return;
        if(VolumeMixer.Visibility == Visibility.Collapsed)
        {
            isAwaitVolumeGaugeRunning = true;
            VolumeMixer.Visibility = Visibility.Visible;
            DoubleAnimation fadeIn = new DoubleAnimation(0, 1, TimeSpan.FromSeconds(0.1), FillBehavior.Stop);
            fadeIn.Completed += (object senderr, EventArgs ee) => { VolumeMixer.Opacity = 1; };
            VolumeMixer.BeginAnimation(OpacityProperty, fadeIn);
            Fadeout();
            return;
        }
        if (e.Delta > 0)            
            workingResources.MasterVolumeValue += 5;
        else
            workingResources.MasterVolumeValue -= 5;
    }

    private async Task Fadeout()
    {
        await Task.Delay(1500);
        if (!isAwaitVolumeGaugeRunning)
            return;
        DoubleAnimation fadeOut = new DoubleAnimation(1, 0, TimeSpan.FromSeconds(0.1), FillBehavior.Stop);
        fadeOut.Completed += (object sender, EventArgs e) => 
        {
            VolumeMixer.Opacity = 0;
            VolumeMixer.Visibility = Visibility.Collapsed;
        };
        VolumeMixer.BeginAnimation(OpacityProperty, fadeOut);
        isAwaitVolumeGaugeRunning = false;
    }

当用户滚动时,Canvas VolumeMixer FadeIn和MasterVolueValue将绑定到TextBlock和Media Element。但是,如果用户在1.5秒后连续滚动Canvas FadeOut和FadeIn(耗时0.2秒)。所以我希望画布在用户完成滚动1.5秒后隐藏

2 个答案:

答案 0 :(得分:1)

如FCin所述,您可以使用CancellationToken。但是,在这种情况下,我想知道按下按钮后是否更好地将消息框变灰?然后在异步操作完成后重新启用按钮。对我来说,这似乎更清晰,然后处理CancellationTokens并重新开始异步过程。

答案 1 :(得分:1)

创建CancellationTokenSource并将其Token属性的值传递给要取消的方法。要中止调用CancellationTokenSource对象的Cancel()方法。

private static CancellationTokenSource _cancellationTokenSource;

private void Btn_Click(object sender, EventArgs e)
{
    if(previousPress)
    {
        _cancellationTokenSource.Cancel();
    }
    _cancellationTokenSource = new CancellationTokenSource();
    TaskMethodAsync(_cancellationTokenSource.Token);
}
private async Task TaskMethodAsync(CancellationToken cancellationToken)
{
    await Task.Delay(1000, cancellationToken);
    MessageBox.Show("Hello World!");
}