c# - 等待/异步问题

标签 c# windows-8 microsoft-metro async-await .net-4.5

我在 Windows 8 CP 上工作,发现在我的应用程序中,我无法正确地让新的异步/等待机制工作。

我向您展示的这种方法在作为单元测试(从单元测试调用)运行时会起作用,但在正常运行时,它不起作用!

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!
}

什么给了?

最佳答案

我认为您必须将 await 放在 Start 函数中初始 SomeMethod 调用的前面:

await SomeMethod();

关于c# - 等待/异步问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9704873/

相关文章:

c# - 双向链表到 JSON

c# - 创建带有更新下载进度条的 ListView Windows 8 C# XAML

c# - 如何从 xml 中获取数据,通过 linq,c#

c# - ListView 项目绑定(bind)

c# - 如何在应用程序内实现交互式教程?

c++ - 如何以编程方式将应用程序图标固定到 Windows 8 中的 Metro 启动屏幕

windows - 是否可以使用 Visual Studio 11 模拟器的多个实例来调试多人 Metro 应用程序?

c++ - Windows::基础::日期时间

C#:从 Unity 上传照片到 Twitter

windows-8 - 提供 Windows 8 应用程序和桌面应用程序