2

I'm trying to create an app which uses single sign on with live connect and registers the user automatically based on his live connect information.

Right when my application starts I call my LiveConnectViewModel and call those two functions:

        public async void AuthInitialize() 
    {
        string[] scopes = new[] { "wl.signin", "wl.basic", "wl.photos", "wl.emails", "wl.skydrive" };

        liveAuthClient = new LiveAuthClient();
        LiveLoginResult liveLoginResult = await liveAuthClient.InitializeAsync(scopes);

        if (liveLoginResult.Status == LiveConnectSessionStatus.Connected)
        {
            App.Session = liveLoginResult.Session;
        }
        else 
        {
            liveLoginResult = await liveAuthClient.LoginAsync(scopes);
            App.Session = liveLoginResult.Session;
        }
        await LoadProfileAsync();
    }

    public async Task LoadProfileAsync() 
    {
        LiveConnectClient client = new LiveConnectClient(App.Session);
        LiveOperationResult liveOperationResult = await client.GetAsync("me");
        LiveOperationResult liveOperationResultPicture = await client.GetAsync("me/picture");
        dynamic dynResult = liveOperationResult.Result;
        dynResult.picture = liveOperationResultPicture.Result;
        User currentUser = await UserViewModel.findOrCreateUserAsync(dynResult);
        App.currentUser = currentUser;
    }

Right after that another method is invoked when the splash screen disappeared and my View comes up.

This execute that code:

        public ProfilePageViewModel()
    {
        this.CurrentUser = App.currentUser;
    }

Now my overall problem is the timing here. When I debug my application I can see that my LiveConnectViewModel gets called first and makes the initial connect, then the LoadProfileAsync gets executed until my program reaches the first await statement.

Immediately when reaching this point my application stops working on this call and goes on. Now when it comes to my ProfilePageViewModel and it should set my "CurrentUser" Property the await still didn't returned my User to my App.CurrentUser Property which is why it says it's null.

Normally I would just wait until the App.CurrentUser Property is set to something else than null, but I can't get rid of the strange feeling that I either missed to implement the MVVM Pattern right or that I did something extremely wrong with await and async...

Can anyone help me clarify this behavior?

4

1 回答 1

4

正如我在最近的 MSDN 文章中所描述的那样,您应该避免async void使用。

一旦您使用AuthInitializeAsyncreturnTask而不是void,那么您可以await在创建视图模型之前使用它。

于 2013-07-24T23:27:44.463 回答