TPL和XmlSerialization

时间:2014-03-25 12:02:19

标签: c# xml-serialization task-parallel-library xmlserializer

我试图将我的序列化方法编写如下:

public Task<string> Serialize(object objectToSerialize)
{
    if (objectToSerialize == null)
    {
        throw new ArgumentNullException("objectToSerialize");
    }

    Task<string> serialize = new Task<string>(
        () =>
        {
            using (StringWriter stringwriter = new StringWriter())
            {
                XmlSerializer xmlSerializer = new XmlSerializer(objectToSerialize.GetType());
                xmlSerializer.Serialize(stringwriter, objectToSerialize);

                return stringwriter.ToString();
            }
        });

    return serialize;
}

public Task<T> DeserializeObjectAsync<T>(string xml) where T : class
{
    if (string.IsNullOrEmpty(xml))
    {
        return Task.FromResult<T>(null);
    }

    return new Task<T>(() =>
    {
        using (StringReader reader = new StringReader(xml))
        {
            using (XmlReader xmlReader = XmlReader.Create(reader))
            {
                XmlSerializer serializer = new XmlSerializer(typeof(T));
                T theObject = (T)serializer.Deserialize(xmlReader);

                return theObject;
            }
        }
    });
}

我找不到有关如何操作的任何信息。有什么你可以发现没有按照它应该做的吗? 你能提出更好的建议吗?

0 个答案:

没有答案