Reputation:
Consider this code:
private static void Main(string[] args)
{
var person = new Person { Manager = new Manager { Name = "Shahrooz" }, Name = "Sina" };
Console.WriteLine("I am {0} my manager is {1}", person.Name, person.Manager.Name);
//Outpu:I am Sina my manager is Shahrooz
var newManager = person.Manager;
person.Manager = null;
new Thread(() => File.WriteAllText( Path.Combine("C:\\", string.Format("{0}.txt", person.Name)), new JavaScriptSerializer().Serialize(person))).Start();
Console.WriteLine("I am {0} my manager is", person.Name);
person.Manager = newManager;
Console.ReadLine();
}
}
public class Person
{
public string Name { get; set; }
public Manager Manager { get; set; }
}
public class Manager
{
public string Name { get; set; }
}
I am trying to serialize an object with JavaScriptSerializer
. Before serializing I set person's manager to null but I get wonderful results in text file:
{"Name":"Sina","Manager":{"Name":"Shahrooz"}}
I mixed up. Please help me.
Update:
I change my code.that is ok:
internal class Program
{
private static void Main(string[] args)
{
var person = new Person { Manager = new Manager { Name = "Shahrooz" }, Name = "Sina" };
Console.WriteLine("I am {0} my manager is {1}", person.Name, person.Manager.Name);
//Outpu:I am Sina my manager is Shahrooz
var x = person.Manager;
person.Manager = null;
add(person);
Console.WriteLine("I am {0} my manager is", person.Name);
person.Manager = x;
Console.ReadLine();
}
public static async void add(Person person)
{
await AddToFile(person);
}
private async static Task AddToFile(Person person)
{
File.WriteAllText(Path.Combine("C:\\", string.Format("{0}.txt", person.Name)), new JavaScriptSerializer().Serialize(person));
}
}
public class Person
{
public string Name { get; set; }
public Manager Manager { get; set; }
}
public class Manager
{
public string Name { get; set; }
}
Upvotes: 0
Views: 149
Reputation: 72215
The problem is that the thread you create to serialize the object races with the main thread. Sometimes it will serialize the object before the main thread resets the Manager reference, sometimes after.
Here are some solution ideas:
Upvotes: 6
Reputation: 1422
because your manager has a same reference to newManager and actually manager is not null.
Upvotes: 0