How to abort a async / await outside of it method

I have 1 method and 1 event

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

When the user scroll, the Canvas VolumeMixer FadeIn and the MasterVolueValue is Bind to a TextBlock and a Media Element. But if while user are continuously scrolling after 1.5 sec the Canvas FadeOut and FadeIn (took 0.2 sec). So I want The canvas Hide after user complete scrolling 1.5 second

Upvotes: 0

Views: 417

Answers (2)

renklus
renklus

Reputation: 843

Create a CancellationTokenSource and pass the value of it's Token property to the method you want to cancel. To abort call the Cancel() method of your CancellationTokenSource object.

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!");
}

Upvotes: 1

Andrew
Andrew

Reputation: 1621

As FCin mentioned, you can use CancellationToken. However, in this scenario, I'm wondering if it would be better to gray out the message box as soon as the button is pressed? Then reenable the button once the async operation is completed. To me, that seems cleaner then dealing with CancellationTokens and restarting the async process all over again.

Upvotes: 1

Related Questions