Search code examples
c#taskgeneric-method

Creating async version of a generic method


I have this generic method for Deserializing a type

public static T Deserialize<T>(string xmlString)
{
    if (string.IsNullOrWhiteSpace(xmlString))
       return default(T);

    using (MemoryStream memStream = new MemoryStream(Encoding.Unicode.GetBytes(xmlString)))
    {               
       memStream.Position = 0;
       System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(T));
            return (T)serializer.Deserialize(memStream);                
    }
}

Now I wish to make an async version which I tried like this.

public static Task DeserializeAsync(string xmlString)
{
    return Task.Run(() =>
    {
       Deserialize(xmlString));
    });
}

Obviously the async method has syntax errors because I am missing T.

I also tried this and I get errors.

public static Task<T> DeserializeAsync(string xmlString)
{
   return Task.Run(() =>
   {
      Deserialize<T>(xmlString));
   });
}

Can anyone show me the correct way of writing the async method?


Solution

  • You are just forgetting to declare your method as generic (note the <T>), and actually return the result of Deserialize:

    public static Task<T> DeserializeAsync<T>(string xmlString)
    {
       return Task.Run(() =>
       {
          return Deserialize<T>(xmlString));
       });
    }
    

    or more simply:

    public static Task<T> DeserializeAsync<T>(string xmlString)
    {
       return Task.Run(() => Deserialize<T>(xmlString)));
    }