aaubry / YamlDotNet

YamlDotNet is a .NET library for YAML
MIT License
2.48k stars 466 forks source link

Is the IDeserializer thread safe? #896

Closed jackfiled closed 5 months ago

jackfiled commented 5 months ago

Describe the bug I write a code trying to deserialize with Parallel.ForEach but it ran into an exception that:

System.IndexOutOfRangeException: Index was outside the bounds of the array.
   at System.Collections.Generic.Dictionary`2.TryInsert(TKey key, TValue value, InsertionBehavior behavior)
   at System.Collections.Generic.Dictionary`2.set_Item(TKey key, TValue value)
   at YamlDotNet.Serialization.ObjectFactories.DefaultObjectFactory.GetStateMethods(Type attributeType, Type valueType)
   at YamlDotNet.Serialization.ObjectFactories.DefaultObjectFactory.ExecuteState(Type attributeType, Object value)
   at YamlDotNet.Serialization.ObjectFactories.DefaultObjectFactory.ExecuteOnDeserializing(Object value)
   at YamlDotNet.Serialization.NodeDeserializers.ObjectNodeDeserializer.Deserialize(IParser parser, Type expectedType, Func`3 nestedObjectDeserializer, Object& value)
   at YamlDotNet.Serialization.ValueDeserializers.NodeValueDeserializer.DeserializeValue(IParser parser, Type expectedType, SerializerState state, IValueDeserializer nestedObjectDeserializer)

To Reproduce This is a minimal Program.cs to reproduce this question:

using YamlDotNet.Serialization;
using YamlDotNet.Serialization.NamingConventions;

DeserializerBuilder builder = new DeserializerBuilder()
    .WithNamingConvention(CamelCaseNamingConvention.Instance)
    .IgnoreUnmatchedProperties();
IDeserializer deserializer = builder.Build();

List<int> array = [1,2,3,4,5,6,7,8];
const string content = "title: 123123123";

Parallel.ForEach(array, _ =>
{
    Model model = deserializer.Deserialize<Model>(content);
    Console.WriteLine(model.Title);
});

public class Model
{
    public string? Title { get; set; }
}
filzrev commented 5 months ago

I have previously asked a similar question. The answer is that it is not thread-safe. https://github.com/aaubry/YamlDotNet/discussions/844

jackfiled commented 5 months ago

I have previously asked a similar question. The answer is that it is not thread-safe. #844

Fine, thank you very much.