WP8.1 - CancellationToken and async still wait forever and never end

I have a really weird problem and I don't know how to solve it. I have two methods in different classes. The first one fires when a button is pressed in the CommandBar.

EDIT: I created two similar but smaller methods to show you the problem:

    private async void runCode(object sender, RoutedEventArgs e)
    {
        BottomAppBar.IsEnabled = false;
        object result = await endlessLoopTest();
        BottomAppBar.IsEnabled = true;
    }

    private async Task<object> endlessLoopTest()
    {
        var tokenSource = new System.Threading.CancellationTokenSource(500);
        try
        {
            await Task.Run(() =>
            {
                while (true)
                {
                    //Infinite loop to test the code
                }
            }, tokenSource.Token);
            return null;
        }
        catch (OperationCanceledException)
        {
            return new TextBlock();
        }
    }

      

I added a cancelationToken which will expire after 1500ms (I guess if the interpreter takes longer to process the code, it gets caught in a loop).

The first time I try this it usually works, but if I try again the CommandBar buttons will never be enabled again, so I assume the task is waiting forever and I don't know why as I added that cancelationToken ...

Do you know what might be wrong here? Thank you for your help!

Sergio

+3


source to share


1 answer


You are about 2/3 of the way there. When using CancellationToken

+ CancellationTokenSournce

, the token must be requested if it has been canceled. There are several ways to subscribe to this, including calling the token method ThrowIfCancelledRequest or checking the Boolean

IsCancellationRequested token property and break

from within a loop. See Cancellation in Managed Threads .

Here is a small example that can be run in a console application. Note that in UI based apps await

, use rather than Task.Wait()

.



    private static void CancelTask()
    {
        CancellationTokenSource cts = new CancellationTokenSource(750);
        Task.Run(() =>
        {
            int count = 0;
            while (true)
            {
                Thread.Sleep(250);
                Console.WriteLine(count++);
                if (cts.Token.IsCancellationRequested)
                {
                    break;
                }
            }
        }, cts.Token).Wait();
    }

      

Result 0 1 2

and then exit program and program.

+5


source







All Articles