【问题标题】:How to cancel windows phone task that uses await如何取消使用等待的 Windows Phone 任务
【发布时间】:2013-09-16 00:05:19
【问题描述】:

我有这段代码启动一个任务线程,该线程调用一个方法来读取 StreamSocket 中的数据,只要它可用。 Iy 还需要一个取消令牌。

await Task.Factory.StartNew(ProcessMessage, CancelToken);

但是在我调用这个方法之后。

CancelToken.Cancel();

当我在 StreamSocket 中获取新数据时,我的应用程序仍然运行 ProcessMessage 方法。这不应该发生。它认为它是因为我在它上面使用了等待。

令牌被取消后,如何让这个任务停止?

【问题讨论】:

标签: c# windows-phone-7 task


【解决方案1】:

当您发出CancellationToken.Cancel() 时,取消令牌的每个副本上的IsCancellationRequested 属性都设置为true。接收通知的对象可以以任何适当的方式响应。典型的模式是在循环中的某处调用token.ThrowIfCancellationRequested()

所以在你的 ProcessMessage 例程中,你需要类似的东西

while (processing) 
{
    // carry on your processing...

    // Poll on this property if you have to do other cleanup before throwing. 
    if (token.IsCancellationRequested)
    {
        // Clean up here, then...
        token.ThrowIfCancellationRequested();
    }
}

您可以使用 await in the MSDN documentation 找到实施取消的指南。

【讨论】:

  • 感谢您的回答。但这不起作用。即使在我取消令牌后它仍然会处理消息。这是我的 ProcessMessage 类:pastebin.com/uAXjy8sW
  • 您忽略了OperationCancelledException 和您的catch。要么删除它,要么再次throw。如果这可能是一个冗长的操作,您可能还需要在 serverRequest(msg)ThrowIfCancellationRequested()
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-09
  • 1970-01-01
相关资源
最近更新 更多