【发布时间】:2015-09-13 13:52:40
【问题描述】:
我正在 WP8.1 上编写一个小型 GPS 跟踪应用程序,但遇到了一些问题。 我可以在任务中创建并使用它做任何我需要的事情,但我无法取消它。 作为参考,我使用了这个answer
这是我使用的任务构造函数(也尝试使用 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);
}
我在主类部分创建了 tokenSource 对象作为公共变量,以便能够通过 button_click 停止方法访问它(否则我无法使用 tokenSource.Cancel())
当我在构造方法中使用 tokenSource.Cancel() 时,一切正常。 但是当我尝试像这样通过 Button_click 使用它时:
private void Button_Stop(object sender, RoutedEventArgs e)
{
tokenSource.Cancel();
}
什么都没有发生。谁有解决办法?
这是否意味着如果您每次使用 async() 创建一个带有新令牌和按钮单击方法的新线程,我将取消原来的线程线程已经关闭?如果是这样,有什么想法可以解决这个问题吗?
【问题讨论】:
标签: c# multithreading windows-phone-8.1 task-parallel-library task