简体   繁体   中英

Win8 C# trouble with async/await

Why in the second case the exception is thrown?

async void f() {
    await media.InitializeAsync();
    isInit = true;
    capturePreview.Source = media;
    await media.StartPreviewAsync(); // Ok
}

// ------------------------------------------

void f() {
    StaticClass.g(capturePreview.Source);
}

public static class StaticClass {
    public static async void g(MediaSource source) {
        await media.InitializeAsync();
        isInit = true;
        source = media;
        await media.StartPreviewAsync(); // Unknown Exception (It's seems that media isn't init)
    }
}

The f() function use a function which include async . So I think the f() should be signed async as well. Like this: void async f(){...}

If you really want media to be initialized, why don't you do the rest of the code in the .done function ?

 void f() {
     StaticClass.g(capturePreview.Source);
    }

  public static class StaticClass {
     public static async void g(MediaSource source) {
       media.InitializeAsync().done(
       isInit = true;
       source = media;
       await media.StartPreviewAsync(););
     }
  }

Even if I'm not fully sure you can do an async within a done callback.

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