Sergii Bidnyi
Sergii Bidnyi

Reputation: 306

ExecuteXmlReaderAsync doesn't work as expected

I'm trying to implement XML reading from MSSQL using new async methods in .NET 4.5.

I have the following code

var xmlReader = await sqlCommand.ExecuteXmlReaderAsync();

while (await xmlReader.ReadAsync())
{
    var doc = (MyDocument)xmlSerializer.Deserialize(xmlReader);
    await Process(doc);
}

and it fails with Set XmlReaderSettings.Async to true if you want to use Async Methods..

I have checked decompiled sources of ExecuteXmlReaderAsync and I can see that it uses one of this settings:

private static readonly XmlReaderSettings DefaultXmlReaderSettings = new XmlReaderSettings()
{
  ConformanceLevel = ConformanceLevel.Fragment
};
private static readonly XmlReaderSettings DefaultXmlReaderSettingsCloseInput = new       XmlReaderSettings()
{
  ConformanceLevel = ConformanceLevel.Fragment,
  CloseInput = true
};

so it looks like ExecuteXmlReaderAsync is not implemented well.

Please advice if you have any experience to use this method successfully.

UPD: xmlReader.Settings.Async is readonly so it should be set when the object is created

Upvotes: 3

Views: 1039

Answers (1)

svick
svick

Reputation: 244777

I think you're exactly right about the source of this problem. If I use reflection to change the settings in the private field you mentioned, it seems to work.

var settingsField = typeof(SqlXml)
    .GetField("DefaultXmlReaderSettingsCloseInput",
              BindingFlags.Static | BindingFlags.NonPublic);
var settings = (XmlReaderSettings)settingsField.GetValue(null);
settings.Async = true;

Note that this is a dirty hack, which may stop working at any moment. And I don't really know what I'm doing, so this may not actually work properly, or it might have some unintended consequences. Because of that, I would be very careful when using this.

Also, I think you should report this as a bug to Microsoft.

Upvotes: 2

Related Questions