等待/异步问题

时间:2012-03-14 15:27:28

标签: c# windows-8 microsoft-metro async-await .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!
}

是什么给出了?

4 个答案:

答案 0 :(得分:5)

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

await SomeMethod();

答案 1 :(得分:2)

我认为DanielSchlößer的答案可能还有其他一些问题。 以下是我改进的方法:

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

应该在开始时使用“await”调用异步函数。但是使用异步函数的函数也应该签名为“async”。

这是我的观点。感谢

答案 2 :(得分:0)

由于您在调用SomeOtherMethod之前听起来想要完成SomeMethod,因此您需要让它返回一个Task并等待该任务完成。您需要做的就是更改“异步空白”。在声明中的“异步任务”#39;然后在Start方法中,将调用者更改为SomeMethod()。Wait();

就目前而言,既然你没有等待完成任务的任何事情,一旦方法退出(点击第一次等待),就没有什么可以阻止&#39;阻止&#39;其他任何事情都已完成。

使用&#39; async void&#39;意味着你在完成时不关心(或者甚至,如果完成)。如果你关心,你需要使用&#39;异步任务&#39;然后适当地使用它。

不确定它是否有帮助解释,但这是我在这个主题上做过的博文:

http://blog.sublogic.com/2012/03/06/async-lesson-2-of-n-async-void-probably-isnt-what-you-want/

答案 3 :(得分:0)

我认为你应该编辑:

StreamSocket _client;

private async Task Start() {
    await SomeMethod();
     SomeOtherMethod();
}

private async Task 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!
}

我希望能帮到你