SerializeObject is waiting forever

I have a function that serializes objects. It works fine in every case, except when I run a specific object. This is an object of the class that contains Tasks. But I do not understand why this will be a problem.

In debug mode, the code simply gets stuck without any error or any exception. Just stop and wait. We also mention that this serialization is called at the start of the Task, but I'm also not sure why this will be a problem.

I also set the [NonSerialized] attribute for all Task properties, but still nothing.

[NonSerialized]
private Task<bool> isConnected;
public Task<bool> IsConnected
{

    get { return isConnected; }
    set { isConnected = value; }
} 

This is my function:

public static string ToJson(this object obj)
{
    try
    {
        var res = JsonConvert.SerializeObject(obj, Formatting.Indented,
            new JsonSerializerSettings
            {
                ReferenceLoopHandling = ReferenceLoopHandling.Ignore
            });

        return res;
    }
    catch
    {
        return $"Object {obj.ToString()} is not serializable.";
    }
}

This is the object I'm trying to serialize:

+4
source share
1 answer

NonSerialized BinaryFormatter SoapFormatter, Newtonsoft Json.

, , Task ignore, rwad JsonConvert.

.

JsonIgnore, Newtonsoft. DataContract DataMember, System.Runtime.Serialization, , . Task<T> NOT .

JsonIgnore:

public class Test
{
    public Test()
    {
       isConnected =new Task<bool>(()=> {return true;});
    }

    public string Foo{get;set;}

    private Task<bool> isConnected;

    [JsonIgnore] // do not serialize
    public Task<bool> IsConnected
    {       
        get { return isConnected; }
        set { isConnected = value; }
    } 
}

DataContract/DataMember:

[DataContract] // serialize this class
public class Test2
{

    public Test2(){
       isConnected =new Task<bool>(()=> {return true;});
    }

    [DataMember] // serialize this property
    public string Foo{get;set;}

    private Task<bool> isConnected;
    // no DataMember so this one isn't serialized 
    public Task<bool> IsConnected
    {
        get { return isConnected; }
        set { isConnected = value; }
    } 
}
+2

Source: https://habr.com/ru/post/1686880/


All Articles