简体   繁体   中英

Downloading a file on app launch WP7

I am trying to log the user in automatically on the spash page before the application launces, however the below code dosent work. I put break points in and it seems loginDone is never called. Very similar code works fine when launched from a button. Is there something special about the Application_Launching method that means it cant download strings? Possibly not everything has been initialised so it wont work but then I would expect it to error.

private void Application_Launching(object sender, LaunchingEventArgs e)
    {
        done = false;

        IsolatedStorageSettings appSettings = IsolatedStorageSettings.ApplicationSettings;
        appSettings.Remove("sid");
        if (appSettings.Contains("username") && appSettings.Contains("password")) {
            WebClient wc = new WebClient();
            wc.DownloadStringCompleted += loginDone;
            wc.DownloadStringAsync(InkBunnyUrls.Login(appSettings["username"].ToString(), appSettings["password"].ToString()));

            for (int i = 0; (i < 60 && !done); i++) {
                Thread.Sleep(TimeSpan.FromSeconds(1));
            }
        }
    }

    private void loginDone(object sender, DownloadStringCompletedEventArgs e)
    {
        IsolatedStorageSettings appSettings = IsolatedStorageSettings.ApplicationSettings;
        XDocument loginxml = XDocument.Parse(e.Result);
        var sid = (loginxml.Descendants("response").Elements("sid")).FirstOrDefault();
        if (sid == null || sid.Value.Length < 1) {
            appSettings.Add("sid", sid.Value);
        }

        done = true;

    }

WebClient isn't as asynchronous as one might expect - it does various things on the UI thread, including the DownloadStringCompleted handling. So whatever it needs to do will be waiting to get hold of the UI thread - which you've blocked for a minute with your for loop.

It's generally a really bad idea to hold up the UI thread like this. I would launch with a splash screen showing "Downloading file..." leaving the UI thread nicely idle and able to process events like the web request completing - and then when the file has finished downloading, you can move onto your "real" first screen.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM