Threading in XMLSerializer

332 Views Asked by At

How is it possible to extend the following code to be executed in a seperate thread?

The methods calling save/load:

    private void Save()
    {
        ClassDiagram diagram = new ClassDiagram();
        diagram.ClassDatas = ClassDatas.ToList();
        diagram.Connectors = Connectors.ToList();

        String filePathAndName = GetSaveFilePathAndName();
        saveLoadSerialization.Save(filePathAndName, diagram);
    }

    private void Open()
    {
        String filePathAndName = GetOpenFilePathAndName();

        ClassDiagram diagram = saveLoadSerialization.Load<ClassDiagram>(filePathAndName);
        ClassDatas = new ObservableCollection<ClassData>(diagram.ClassDatas);
        Connectors = new ObservableCollection<Connector>(diagram.Connectors);
        Connectors.ToList().ForEach(c => { c.From = ClassDatas.Single(cd => cd.Number == c.FromID); c.To = ClassDatas.Single(cd => cd.Number == c.ToID); });

        RaisePropertyChanged("ClassDatas");
        RaisePropertyChanged("Connectors");
    } 

The Save/Load XMLSerializer code looks like this - is the best approach an asynchronous thread?

    public void Save<T>(String filePathAndName, T data)
    {
        try
        {
            using (FileStream file = File.Create(filePathAndName))
            {
                XmlSerializer serializer = new XmlSerializer(typeof(T));
                serializer.Serialize(file, data);
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
        }
    }

    public T Load<T>(string filePathAndName)
    {
        try
        {
            using (FileStream file = File.OpenRead(filePathAndName))
            {
                XmlSerializer serializer = new XmlSerializer(typeof(T));
                return (T)serializer.Deserialize(file);
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
        }

        return default(T);
    }
0

There are 0 best solutions below