等待/异步问题

Bri*_*ang 2 c# async-await microsoft-metro windows-8 .net-4.5

我正在使用Windows 8 CP并发现在我的应用程序中,我无法正常使用新的异步/等待机制.

我展示的这个方法在作为UnitTest(从单元测试中调用)运行时会起作用,但是当正常运行时,它不起作用!

StreamSocket _client;

private void Start() {
     SomeMethod();
     SomeOtherMethod();
}

private async void SomeMethod(string sample)
{
    var request = new GetSampleRequestObject(sample);
    byte[] payload = ConvertToByteArray(request, Encoding.UTF8);

    DataWriter writer = new DataWriter(_client.OutputStream);
    writer.WriteBytes(payload);
    await writer.StoreAsync(); // <--- after this executes, it exits the method and continues
    await writer.FlushAsync(); // <--- breakpoint never reaches here, instead
    writer.DetachStream();
}

private void SomeOtherMethod()
{
    string hello = "hello"; // <--- it skips everything and reaches here!
}
Run Code Online (Sandbox Code Playgroud)

是什么赋予了?

小智 5

我想你必须在Start函数中等待最初的SomeMethod调用:

await SomeMethod();