0

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?

Daniel Kelley
  • 7,579
  • 6
  • 42
  • 50
Gaz83
  • 2,293
  • 4
  • 32
  • 57
  • 3
    Why make it `async`? There is no I/O to wait upon. If the method took a `Stream` instead of a `string`, then you could gain something. – Richard Schneider Feb 26 '15 at 11:08
  • The wait is done in the calling method i.e await DeserializeAsync(blahblah); is that not right? – Gaz83 Feb 26 '15 at 11:11
  • 1
    So what is the calling method waiting upon. The DeserializeAsynch method is CPU intensive so its not able to give time away as it would if it needed to do some I/O. – Richard Schneider Feb 26 '15 at 11:15

1 Answers1

3

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)));
}
Brandon
  • 38,310
  • 8
  • 82
  • 87