简体   繁体   中英

Windows Phone 8.1 GPS background task

I'm writing a little GPS tracking app on a WP8.1 and I hit a bit of a wall. I'm able to create at task and do whatever I need with it but I cannot cancel it. As a reference I was using this answer

This is the task constructor that I user(also tried with TaskFactory):

public async void run()
{
    IProgress<object> progress = new Progress<object>(_ => track()); 
    //Above is needed to be able to update the UI component
          Task.Run(async () =>
    //Need to run async because the task is a GPS position call that has a delay
     {
         while (true)
         {
             await Task.Delay(1000);
             progress.Report(null);
         }
     }, tokenSource.Token);
}

I created the tokenSource object in the main class section as a public variable to be able to access it through a button_click stop method(otherwise I have no ability to use tokenSource.Cancel())

When I use the tokenSource.Cancel() inside the constructor method all is ok. But when I try to use it via the Button_click like this :

private void Button_Stop(object sender, RoutedEventArgs e)
{
    tokenSource.Cancel();
}

Nothing happens. Anyone has any solutions ?

Does this mean that if u use async() every time it creates a new thread with a new token and with a button click methond I'm cancelling the original one from which the thread is already closed ? If so any ideas how to go around this ?

Cancellation in .Net is cooperative. You cancel it from outside and you need to observe the cancellation from within. Right now, you only signal cancellation.

Your task needs to check the token in some way and stop the task:

Task.Run(async () =>
{
    while (true)
    {
        tokenSource.Token.ThrowIfCancellationRequested();
        await Task.Delay(1000);
        progress.Report(null);
    }
}, tokenSource.Token);

Since that's exactly how the Task.Delay overload that accepts a CancellationToken is implemented you can just rely on it to throw the exception:

Task.Run(async () =>
{
    while (true)
    {
        await Task.Delay(1000, tokenSource.Token);
        progress.Report(null);
    }
}, tokenSource.Token);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM