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 ?