Exemplo n.º 1
0
        /// <summary>
        /// Encode
        /// </summary>
        /// <param name="stream"></param>
        /// <param name=""></param>
        /// <param name="codecId"></param>
        public void Encode(Stream stream, CodecId codecId)
        {
            switch (codecId)
            {
            case CodecId.Json:
                using (var writer = new JsonTextWriter(new StreamWriter(stream))
                {
                    CloseOutput = false
                }) {
                    new JsonSerializer()
                    {
                        ContractResolver = CustomResolver.Instance
                    }.Serialize(writer, this as T);
                    writer.Flush();
                }
                break;

            case CodecId.Mpack:
                using (var writer = new MsgPackStream(stream)) {
                    writer.WriteAsync <T>(this as T, CancellationToken.None).GetAwaiter().GetResult();
                }
                break;

            default:
                throw new NotSupportedException();
            }
        }
Exemplo n.º 2
0
        /// <summary>
        /// Encode
        /// </summary>
        /// <param name="stream"></param>
        /// <param name=""></param>
        /// <param name="codecId"></param>
        public async Task EncodeAsync(Stream stream, CodecId codecId, CancellationToken ct)
        {
            switch (codecId)
            {
            case CodecId.Json:
                await Task.Run(() => {
                    using (var writer = new JsonTextWriter(new StreamWriter(stream))
                    {
                        CloseOutput = false
                    }) {
                        new JsonSerializer()
                        {
                            ContractResolver = CustomResolver.Instance
                        }.Serialize(writer, this as T);
                        writer.Flush();
                    }
                }, ct).ConfigureAwait(false);

                break;

            case CodecId.Mpack:
                using (var writer = new MsgPackStream(stream)) {
                    await writer.WriteAsync <T>(this as T, ct).ConfigureAwait(false);
                }
                break;

            default:
                throw new NotSupportedException();
            }
        }