Phi*_*ray 5 .net c# json.net async-await .net-4.5
我已经从 NuGet 编写了一个Json.Net v5.06 的小型异步库包装器,在更新了许多 Telerik 包后,我的 UnitTests 开始失败并出现MissingMethodException。
我创建了一个虚拟的非异步方法,该方法有效,所以我很困惑错误所在。
项目目标平台
.Net 4.5
x86CPU
异步操作
public class JsonSerialiser : ISerialiser
{
[InjectionConstructor]
public JsonSerialiser(IStringCompression streamCompressor, ILog logger)
{
if (streamCompressor == null) throw new ArgumentNullException("streamCompressor");
if (logger == null) throw new ArgumentNullException("logger");
XmlConfigurator.Configure();
this.streamCompressor = streamCompressor;
this.logger = logger;
}
public async Task<string> SerialiseAsync<T>(T serialseObject) where T : class
{
if (serialseObject == null) throw new ArgumentNullException("serialseObject");
try
{
return await JsonConvert.SerializeObjectAsync(serialseObject);
}
catch (JsonSerializationException ex)
{
logger.Error(ex);
throw new SerialisationException("Could Not Serialse The Object", ex);
}
}
}
Run Code Online (Sandbox Code Playgroud)
异步示例
现在,将这段代码放在一起只是为了测试基本序列化,其中我跳过了类构造函数中的空检查。
private async void button1_Click(object sender, EventArgs e)
{
List<Part> parts = new List<Part> { new Part() { AbstractType = typeof(IOpcController), ConcreteType = typeof(OpcController) },
new Part() { AbstractType = typeof(ISerialiser), ConcreteType = typeof(JsonSerialiser) },
new Part() { AbstractType = typeof(IStringCompression), ConcreteType = typeof(StringGZipCompression)}};
string serialisedResult = string.Empty;
JsonSerialiser serialiser = new JsonSerialiser(null, null);
serialisedResult = await serialiser.SerialiseAsync<List<Part>>(parts);
}
Run Code Online (Sandbox Code Playgroud)
异步结果
这会生成一个MissingMethodException

Method not found: 'System.Threading.Tasks.Task`1<System.String> Newtonsoft.Json.JsonConvert.SerializeObjectAsync(System.Object)'.
at Helper.Core.Serialisation.Json.JsonSerialiser.<SerialiseAsync>d__0`1.MoveNext()
at System.Runtime.CompilerServices.AsyncMethodBuilderCore.Start[TStateMachine](TStateMachine& stateMachine)
at System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1.Start[TStateMachine](TStateMachine& stateMachine)
at Helper.Core.Serialisation.Json.JsonSerialiser.SerialiseAsync[T](T serialseObject)
at OpcTester.Form1.<button1_Click>d__9.MoveNext() in c:\Users\phil.murray\Desktop\tmp\OpcTester\Form1.cs:line 44
Run Code Online (Sandbox Code Playgroud)
无 异步操作
只是为了检查是否是方法的异步部分导致了问题,我编写了一个非异步实现。
public string Serialise<T>(T serialseObject) where T : class
{
if (serialseObject == null) throw new ArgumentNullException("serialseObject");
try
{
return JsonConvert.SerializeObject(serialseObject);
}
catch (JsonSerializationException ex)
{
logger.Error(ex);
throw new SerialisationException("Could Not Serialse The Object", ex);
}
}
Run Code Online (Sandbox Code Playgroud)
无 异步实现
private async void button1_Click(object sender, EventArgs e)
{
List<Part> parts = new List<Part> { new Part() { AbstractType = typeof(IOpcController), ConcreteType = typeof(OpcController) },
new Part() { AbstractType = typeof(ISerialiser), ConcreteType = typeof(JsonSerialiser) },
new Part() { AbstractType = typeof(IStringCompression), ConcreteType = typeof(StringGZipCompression)}};
string serialisedResult = string.Empty;
JsonSerialiser serialiser = new JsonSerialiser(null, null);
serialisedResult = serialiser.Serialise<List<Part>>(parts);
}
Run Code Online (Sandbox Code Playgroud)
无 异步结果
该方法完成列表并将其序列化为字符串。
失败的测试示例
Test Name: SerialiserSerialiseObjectExists
Test FullName: Helper.Tests.SerialiserTests.SerialiserSerialiseObjectExists
Test Source: c:\Perforce\Development\SharedAPIs\Helper.Core\Helper.Tests\SerialiserTests.cs : line 38
Test Outcome: Failed
Test Duration: 0:00:00.0116216
Result Message:
Test method Helper.Tests.SerialiserTests.SerialiserSerialiseObjectExists threw exception:
System.MissingMethodException: Method not found: 'System.Threading.Tasks.Task`1<System.String> Newtonsoft.Json.JsonConvert.SerializeObjectAsync(System.Object)'.
Result StackTrace:
at Helper.Core.Serialisation.Json.JsonSerialiser.<SerialiseAsync>d__0`1.MoveNext()
at System.Runtime.CompilerServices.AsyncMethodBuilderCore.Start[TStateMachine](TStateMachine& stateMachine)
a
t System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1.Start[TStateMachine](TStateMachine& stateMachine)
at Helper.Core.Serialisation.Json.JsonSerialiser.SerialiseAsync[T](T serialseObject)
at Helper.Tests.SerialiserTests.<SerialiserSerialiseObjectExists>d__3.MoveNext() in c:\Perforce\Development\SharedAPIs\Helper.Core\Helper.Tests\SerialiserTests.cs:line 40
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
Run Code Online (Sandbox Code Playgroud)
没有 Json.Net 的异步测试
只是为了论证,我用虚拟任务替换了 Json.Net 调用,并且它有效,因此看起来问题在于使用 Await\Async 调用 Json.net。奇怪的是,这是有效的,但版本尚未更新。
public async Task<string> SerialiseAsync<T>(T serialseObject) where T : class
{
if (serialseObject == null) throw new ArgumentNullException("serialseObject");
try
{
//return await JsonConvert.SerializeObjectAsync(serialseObject);
return await Task.Run(() => string.Empty);
}
catch (JsonSerializationException ex)
{
logger.Error(ex);
throw new SerialisationException("Could Not Serialse The Object", ex);
}
}
Run Code Online (Sandbox Code Playgroud)
问题
现在,在我更新 Telerik 控制套件之前,异步方法 UnitTests 以前就可以工作,并且我确实在许多现实世界实例中测试了该操作。我并不是说 Telerik 更新导致了这个问题,因为这可能是一个巧合。在测试其他类(与 Json.Net 无关)时,许多其他异步测试用例都通过了。
知道异步方法有什么问题以及如何解决该问题吗?
可能的解决方案
当我继续调查这个问题时,我发现问题可能出在 Json.Net 库中的异步调用中,因此我将非异步调用包装在任务中,如下所示,它有效
public async Task<string> SerialiseAsync<T>(T serialseObject) where T : class
{
if (serialseObject == null) throw new ArgumentNullException("serialseObject");
try
{
//return await JsonConvert.SerializeObjectAsync(serialseObject);
return await Task.Run<string>(() => JsonConvert.SerializeObject(serialseObject));
}
catch (JsonSerializationException ex)
{
logger.Error(ex);
throw new SerialisationException("Could Not Serialse The Object", ex);
}
}
Run Code Online (Sandbox Code Playgroud)
出于兴趣,我下载了 Json.Net 的源代码并检查了 JsonConvert.SerializeObjectAsync 调用,它做了同样的事情,所以我再次不确定潜在的问题。
public static Task<string> SerializeObjectAsync(object value, Formatting formatting, JsonSerializerSettings settings)
{
return Task.Factory.StartNew(() => SerializeObject(value, formatting, settings));
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3913 次 |
| 最近记录: |