将反序列化方法转换为异步 [英] Convert Deserialization method to Async

查看:77
本文介绍了将反序列化方法转换为异步的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Async/Await将该对象反序列化的方法转换为字符串.

 公共静态T DeserializeObject< T>(字符串xml){使用(StringReader reader = new StringReader(xml)){使用(XmlReader xmlReader = XmlReader.Create(reader)){DataContractSerializer序列化器=新的DataContractSerializer(typeof(T));T theObject =(T)serializer.ReadObject(xmlReader);返回对象;}}} 

解决方案

大多数序列化API没有 async 实现,这意味着您唯一能做的就是 wrap 同步方法.例如:

 公共静态任务< T>DeserializeObjectAsync< T>(字符串xml){使用(StringReader reader = new StringReader(xml)){使用(XmlReader xmlReader = XmlReader.Create(reader)){DataContractSerializer序列化器=新的DataContractSerializer(typeof(T));T theObject =(T)serializer.ReadObject(xmlReader);返回Task.FromResult(theObject);}}} 

这实际上不是 异步-它仅符合所需的API.如果可以选择,在结果可能经常是同步的情况下,最好使用 ValueTask< T>

无论哪种方式,您都应该能够执行以下操作:

  var obj =等待DeserializeObject< YourType>(someXml);Debug.WriteLine(obj.Name);//等等 

无需知道实际实现是同步还是异步.

I am trying to convert this method that deserializes an object into a string with Async/Await.

    public static T DeserializeObject<T>(string xml)
    {
        using (StringReader reader = new StringReader(xml))
        {
            using (XmlReader xmlReader = XmlReader.Create(reader))
            {
                DataContractSerializer serializer = new DataContractSerializer(typeof(T));
                T theObject = (T)serializer.ReadObject(xmlReader);
                return theObject;
            }
        }
    }

解决方案

Most serialization APIs do not have async implementations, which means the only thing you can really do is wrap a sync method. For example:

public static Task<T> DeserializeObjectAsync<T>(string xml)
{
    using (StringReader reader = new StringReader(xml))
    {
        using (XmlReader xmlReader = XmlReader.Create(reader))
        {
            DataContractSerializer serializer =
                new DataContractSerializer(typeof(T));
            T theObject = (T)serializer.ReadObject(xmlReader);
            return Task.FromResult(theObject);
        }
    }
}

This isn't actually async - it just meets the required API. If you have the option, using ValueTask<T> is preferable in scenarios where the result may often be synchronous/

Either way, you should then be able to do something like:

var obj = await DeserializeObject<YourType>(someXml);
Debug.WriteLine(obj.Name); // etc

without needing to know whether the actual implementation was synchronous or asynchronous.

这篇关于将反序列化方法转换为异步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆