private async Task WriteMessageInternalAsync(Message message, Stream stream, string startInfo, string boundary, string startUri, bool writeMessageHeaders) { if (message == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(message))); } if (stream == null) { throw TraceUtility.ThrowHelperError(new ArgumentNullException(nameof(stream)), message); } ThrowIfMismatchedMessageVersion(message); EventTraceActivity eventTraceActivity = null; if (WcfEventSource.Instance.MtomMessageEncodingStartIsEnabled()) { eventTraceActivity = EventTraceActivityHelper.TryExtractActivity(message); WcfEventSource.Instance.MtomMessageEncodingStart(eventTraceActivity); } message.Properties.Encoder = this; if (MessageLogger.LogMessagesAtTransportLevel) { MessageLogger.LogMessage(ref message, MessageLoggingSource.TransportSend); } XmlDictionaryWriter xmlWriter = _factory.TakeStreamedWriter(stream, startInfo, boundary, startUri, writeMessageHeaders); if (_writeEncoding.WebName == "utf-8") { await message.WriteMessageAsync(xmlWriter); } else { await xmlWriter.WriteStartDocumentAsync(); await message.WriteMessageAsync(xmlWriter); await xmlWriter.WriteEndDocumentAsync(); } await xmlWriter.FlushAsync(); _factory.ReturnStreamedWriter(xmlWriter); if (WcfEventSource.Instance.StreamedMessageWrittenByEncoderIsEnabled()) { WcfEventSource.Instance.StreamedMessageWrittenByEncoder(eventTraceActivity ?? EventTraceActivityHelper.TryExtractActivity(message)); } }