【问题标题】:synchronous authorization in WinRtWinRt 中的同步授权
【发布时间】:2013-02-12 23:05:50
【问题描述】:

我基本上是在尝试同步运行我的 WinRt 应用程序的授权过程,但我尝试的所有操作似乎都会在 MainPage 上授权后使应用程序死锁,从而阻止导航到主页。似乎无法弄清楚。这是我没有修改的代码,它在下面异步工作得很好。我怎样才能使这项工作同步:

类:

public async void InitializeTwitterAsnc()
    {

        WinRtAuthorizer authorizer = null;

        authorizer = new WinRtAuthorizer()
        {
            Credentials = new LocalDataCredentials()
            {
                ConsumerKey = "blah379",
                ConsumerSecret = "blah123"
            },
            UseCompression = true,
            Callback = new Uri("http://blah.com")
        };

        if(!authorizer.IsAuthorized)
        {
            await authorizer.AuthorizeAsync();
        }

        // set the twitter credential fields
        await Task.Run
            (() =>
                 {
                     twitterName = authorizer.Credentials.ScreenName;
                     twitterId = authorizer.Credentials.UserId;
                     accessToken = authorizer.Credentials.AccessToken;
                     oAuthToken = authorizer.Credentials.OAuthToken;

                     this.TwitterContext = new TwitterContext(authorizer);
                 });
    }

从 MainPage.xaml.cs 调用方法的代码:

private void StartTwitterLogin(object sender, RoutedEventArgs e)
    {
        // start the twitter authorization
        TwitterAuth twitAuth = new TwitterAuth();
        twitAuth.InitializeTwitterAsnc();


        this.Frame.Navigate(typeof (HomePage));
    }

【问题讨论】:

    标签: c# windows-runtime linq-to-twitter


    【解决方案1】:

    你不能。异步 API 仅意味着异步运行,如果您尝试强制线程等待结果 - 您通常会遇到死锁,因为 API 本身通常需要在您阻塞的线程上运行某些东西。您不应该试图与之抗争,而应该思考您要解决的实际问题是什么。

    在您的情况下,您应该将方法的签名从

    public async void InitializeTwitterAsnc()
    

    public async Task InitializeTwitterAsnc()
    

    这样可以等待,然后在这里等待:

    private async Task StartTwitterLogin(object sender, RoutedEventArgs e)
    {
        // start the twitter authorization
        TwitterAuth twitAuth = new TwitterAuth();
        await twitAuth.InitializeTwitterAsnc();
    
    
        this.Frame.Navigate(typeof (HomePage));
    }
    

    【讨论】:

    • 哇,我以前没见过。谢谢你让我注意到这一点。我想我最初只是过度思考了这个问题,对异步和所有内容都是新手。
    • 您在非异步方法中究竟是如何使用 await 的?
    【解决方案2】:

    所以最终,我的解决方案是在异步 twitAuth.InitializeTwitterAsync() 方法中处理导航。为了使导航工作,我必须在 app.xaml.cs 中创建一个静态框架属性,我可以在我的自定义类中使用它来进行导航。请参阅此链接WinRt page navigaiton

    【讨论】:

      猜你喜欢
      • 2014-12-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-25
      • 1970-01-01
      • 2014-10-20
      • 1970-01-01
      相关资源
      最近更新 更多