locked
Async operations seem to execute synchronously on WP7

    Întrebare

  • I'm trying to use the async CTP to do streaming audio in an XNA game.  I've got a system working using background threads, but it causes hitches, and so I'd like to use the async functionality instead.

    I created a new game project to test async file IO:

            protected override void Update(GameTime gameTime)
            {
                // Allows the game to exit
                if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                    this.Exit();
    
                // TODO: Add your update logic here
    
                Debug.WriteLine("before DoAThingAsync");
                DoAThingAsync();
                Debug.WriteLine("after DoAThingAsync");
    
                base.Update(gameTime);
            }
    
            protected async void DoAThingAsync()
            {
                try
                {
                    Debug.WriteLine("begin DoAThingAsync");
                    byte[] buf = new byte[100];
    #if WINDOWS_PHONE
                    Stream stream = TitleContainer.OpenStream(@"WMAppManifest.xml");
    #else
                    Stream stream = new FileStream(@"c:\assignedtome.psq", FileMode.Open, FileAccess.Read);
    #endif
                    await stream.ReadAsync(buf, 0, 100);
                    await stream.ReadAsync(buf, 100, 0);
                    await stream.ReadAsync(buf, 200, 0);
                    stream.Close();
                    //Thread.Sleep(1000);
                }
                catch (Exception e)
                {
                    Debug.WriteLine(e);
                }
                finally
                {
                    Debug.WriteLine("end DoAThingAsync");
                }
            }

    On Windows, I get this output: 

    before DoAThingAsync
    begin DoAThingAsync
    after DoAThingAsync
    end DoAThingAsync

    On WP7, I get this output:

    before DoAThingAsync begin DoAThingAsync end DoAThingAsync after DoAThingAsync

    Notice that, on WP7, the entire DoAThingAsync() function executes before control returns to Update(), but on Windows, the expected behavior (control returning to Update() before the async work finishes.


    31 martie 2012 01:31

Toate mesajele

  • It seems that using Stream.BeginRead() (which didn't used to be available on WP7, I'm assuming it was made available with the Async CTP) works, and the callback comes from the main thread, so perhaps it's using an async task under the hood?

    If using BeginRead()/EndRead() solves my problem, then great.  But I'd still like to know why await doesn't seem to do the right thing on WP7.

    31 martie 2012 17:18