andcontinue() - 作为异步操作执行的方法

时间:2014-05-12 16:08:41

标签: c# windows-phone-8 asynchronous windows-phone-8.1

对于Windows Phone 8.1,微软推出了一些以AndContinue结尾的方法。这些方法暂停应用程序以执行和处理用户输入。之后,他们使用包含操作结果的对象调用Continue... - 方法。

示例为WebAuthenticationBroker.AuthenticateAndContinue,用于OAuth。

示例代码:

class Test : IWebAuthenticationContinuable
{
    private void StartAuth()
    {
        WebAuthenticationBroker.AuthenticateAndContinue(new Uri("http://example.org/token?someInformations"),
                new Uri("http://example.org/callback"), null, WebAuthenticationOptions.None);
    }

    private void ContinueWebAuthentication(WebAuthenticationBrokerContinuationEventArgs args)
    {
        WebAuthenticationResult result = args.WebAuthenticationResult;

        //Do something with the result
    }
}

在Windows应用商店中,使用WebAuthenticationBroker.AuthenticateAsync - emthod可以获得同样的效果。这种方法是一种简单的异步操作。

我想使用AuthenticateAsync为Windows Phone写一个AuthenticateAndContinue方法。它必须返回Task<WebAuthenticationResult>

作为一种非常黑客的方法,我想到了Task,它在执行ContinueWebAuthentication后完成。如果我等待这个任务并将结果设置为某个变量,我可以在异步方法中访问它并返回它。

但我无法弄清楚如何实现这一点。

1 个答案:

答案 0 :(得分:4)

AndContinue API不是Windows Store AuthenticateAsync之类的异步调用。 From MSDN

  

当您调用AndContinue方法时,您的应用会在操作完成时停用,以节省内存。在低内存设备上,您的应用甚至可能会被终止。

因此,当您调用AndContinue方法时,您的应用可以终止。恢复应用后,您需要采用某种方式重新启动async方法。没有像这种内置的AFAIK。

使用Task<WebAuthenticationResult>创建TaskCompletionSource<T>当然是可能的,但在这种情况下不起作用。 AndContinue方法可以终止您的应用,当您的应用恢复时,它可以完成任务,但不会有任何async方法等待它。

你可能有一个在暂停/恢复时被序列化的“任务缓存”,并且你的async方法从该缓存拉出,只有在找不到任务的情况下调用其他async方法。我会说这种方法充满了陷阱,但完全不值得。