我写了一个简单的服务,可以使用默认的XmlSerializer对类进行序列化和反序列化。我想异步执行此操作,但是当XMlSerializer在Task中引发异常时,try / catch不会捕获该异常
public async Task<T> DeserializeAsync<T>(TextReader reader)
{
try
{
return await Task.Run(() =>
{
var serializer = new XmlSerializer(typeof(T));
var result = serializer.Deserialize(reader);
return (T) result;
});
}
catch (Exception e)
{
//Do something with exception
}
}
我有一个解决方案,但不可能是这个问题的解决方案:
public async Task<T> DeserializeAsync<T>(TextReader reader)
{
Exception exception = null;
var result = await Task.Run(
() =>
{
try
{
return (T) new XmlSerializer(typeof(T)).Deserialize(reader);
}
catch (Exception e)
{
exception = e;
return default(T);
}
});
if (exception != null)
{
// handle exception
}
return result;
}
更新:再现错误的代码:
using System;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
public class Program
{
private static Serializer _serializer;
static void Main(string[] args)
{
_serializer = new Serializer();
Task.Factory.StartNew(ReadUsers);
Console.ReadKey();
}
private static async Task ReadUsers()
{
var stream = new MemoryStream(Encoding.ASCII.GetBytes(""));
try
{
var user = await _serializer.DeserializeAsync<User>(new StreamReader(stream));
Console.WriteLine(user.Name);
}
catch (Exception e)
{
Console.WriteLine($"Caught exception: {e.Message}");
}
}
}
public class Serializer
{
public async Task<T> DeserializeAsync<T>(TextReader reader)
=> await Task.Run(() => (T) new XmlSerializer(typeof(T)).Deserialize(reader));
}
public class User
{
public string Name { get; set; }
public int Age { get; set; }
}