在TCP读取请求中的意外时间调用了一个方法

时间:2012-11-27 16:10:36

标签: c# asynchronous windows-phone-8

StreamSocket _connection = AsyncCreateConnection(); // In constructor

private async void receive(){
DataReader reader = new DataReader(_connection.InputStream);
DataWriter writer = new DataWriter(_connection.OutputStream);

try
        {
            reader.InputStreamOptions = InputStreamOptions.Partial;
            uint sizeFieldCount = await reader.LoadAsync(sizeof(uint)); // <<--  Explosion
            if (sizeFieldCount != sizeof(uint))
            {
                return;
            }

            // Read the string.
            uint stringLength = reader.ReadUInt32();
            uint actualStringLength = await reader.LoadAsync(stringLength);
            if (stringLength != actualStringLength)
            {
                return;
            }

            Debug.WriteLine(reader.ReadString(actualStringLength));
        }
        catch (Exception exc)
        {
            Debug.WriteLine(exc.Message);
        }
}

整个下午都收到了这个错误。调用receive方法时,应该完成创建连接的异步。

1 个答案:

答案 0 :(得分:0)

例外情况是说您在准备好之前使用async来电的输出。

我相信您的连接尚未就绪,也许您应该await连接。

因为构造函数不能是async,所以你需要从另一个函数调用它。

StreamSocket _connection = await AsyncCreateConnection();