简体   繁体   English

Windows Phone 8.1 GPS后台任务

[英]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. 我在WP8.1上编写了一个GPS跟踪应用程序,但遇到了一些困难。 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): 这是我使用的任务构造函数(也可以通过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()) 我在主类部分中将tokenSource对象创建为公共变量,以便能够通过button_click stop方法访问它(否则,我将无法使用tokenSource.Cancel())

When I use the tokenSource.Cancel() inside the constructor method all is ok. 当我在构造方法中使用tokenSource.Cancel()时,一切正常。 But when I try to use it via the Button_click like this : 但是当我尝试通过Button_click像这样使用它时:

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 ? 这是否意味着如果您每次使用async()每次创建带有新令牌并单击按钮的新线程时,我都将取消已关闭该线程的原始线程? If so any ideas how to go around this ? 如果有的话,如何解决这个问题?

Cancellation in .Net is cooperative. .Net中的取消是协作的。 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: 由于这正是实现CancellationTokenTask.Delay重载的完全实现方式,因此您可以仅依靠它引发异常:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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