Exemplo n.º 1
0
        /// <summary>
        /// Create message from stream using specified codec.
        /// </summary>
        /// <param name="stream"></param>
        /// <param name="codecId"></param>
        /// <returns></returns>
        public static Task <T> DecodeAsync(Stream stream, CodecId codecId, CancellationToken ct)
        {
            switch (codecId)
            {
            case CodecId.Json:
                var tcs = new TaskCompletionSource <T>();
                Task.Run(() => {
                    using (var reader = new JsonTextReader(new StreamReader(stream))
                    {
                        CloseInput = false
                    }) {
                        tcs.TrySetResult(new JsonSerializer()
                        {
                            ContractResolver = CustomResolver.Instance
                        }.Deserialize <T>(reader));
                    }
                }, ct);
                return(tcs.Task);

            case CodecId.Mpack:
                using (var reader = new MsgPackStream(stream)) {
                    return(reader.ReadAsync <T>(ct));
                }

            default:
                throw new NotSupportedException();
            }
        }
Exemplo n.º 2
0
        /// <summary>
        /// Create message from stream using specified codec.
        /// </summary>
        /// <param name="stream"></param>
        /// <param name="codecId"></param>
        /// <returns></returns>
        public static T Decode(Stream stream, CodecId codecId)
        {
            T decoded;

            switch (codecId)
            {
            case CodecId.Json:
                using (var reader = new JsonTextReader(new StreamReader(stream))
                {
                    CloseInput = false
                }) {
                    decoded = new JsonSerializer()
                    {
                        ContractResolver = CustomResolver.Instance
                    }.Deserialize <T>(reader);
                }
                break;

            case CodecId.Mpack:
                using (var reader = new MsgPackStream(stream)) {
                    decoded = reader.ReadAsync <T>(CancellationToken.None).GetAwaiter().GetResult();
                }
                break;

            default:
                throw new NotSupportedException();
            }
            return(decoded);
        }