Skip to main content
 首页 » 编程设计

c#之andcontinue()之作为异步操作执行的方法

2024年02月13日12linjiqin

对于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 可以实现同样的效果-方法。此方法是一个简单的异步操作。

我想写一个AuthenticateAsync -Windows 手机的方法使用 AuthenticateAndContinue .它必须返回 Task<WebAuthenticationResult> .

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

但我无法弄清楚如何实现它。

请您参考如下方法:

AndContinue API 不是像 Windows 应用商店那样的异步调用 AuthenticateAsync是。 From MSDN :

When you call an AndContinue method, your app is deactivated while the operation completes in order to conserve memory. On low-memory devices, your app might even be terminated.

因此,当您调用 AndContinue方法,您的应用程序可以终止。当您的应用程序恢复时,您将需要某种方式跳回到您的 async。方法。没有什么比这个内置的 AFAIK 更好的了。

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

你可能有一个在挂起/恢复时序列化的“任务缓存”,并且有你的async方法从该缓存中提取,调用其他 async只有在找不到任务时才调用方法。不过,我会说这种方法充满了陷阱,而且完全不值得。