问题描述
我遇到了无法使用 System.Text.Json
(.Net 5)将字符串反序列化为Task的问题.
I'm running into a problem where I can't deserialize a string into a Task using System.Text.Json
(.Net 5).
JsonSerializer.Deserialize<Task<TItem>>(serializedItem)
背景
我有一个本地化的缓存,并在其中存储了从数据库中检索到的项目.
Background
I have a localized cache and store in it items retrieved from the DB.
我无法将实际项目存储在缓存中,因为对对象的任何后续操作都会导致对缓存项目进行操作,从而影响所有进一步的使用.因此,我存储了该对象的序列化副本.
I can't store the actual item in the cache, because any subsequent manipulation of the object results in the cached item being manipulation, affecting all further uses. I therefore store a serialized copy of the object.
关于性能...
我正在使用异步/等待模式来调用数据库(整个应用程序都是异步的).
I'm using the async/await pattern to call the DB (the whole app is async).
我读了一篇文章(可能是一段视频),其中斯蒂芬·图卜(Stephen Toub)描述了缓存任务的性能优势.这样的SO文章何时缓存任务?进行了详细介绍.无论如何,我以为我会尝试在本地缓存层"中使用以下代码(无需序列化即可完美工作):
I read an article (may have been a video) in which Stephen Toub described the performance advantage of caching the Task. This SO article When to cache Tasks? goes into the details. Anyhow, I thought I'd try to take advantage of this (it works perfectly without serialization) using the following in my local cache "layer":
- 如果Task在我的缓存中,请等待它并返回结果.
- 否则,无需等待就调用数据库方法,并将结果任务添加到缓存中
当我添加序列化时,然后反序列化任务:
When I add serialization, then the deserialization of the task:
Task<TItem>? cachedItem = JsonSerializer.Deserialize<Task<TItem>>(serializedItem);
产生
推荐答案
答案很简单-序列化Task结果中的数据,而不是任务本身.
The answer here is relatively straightforward - serialize the data inside the Task result, not the task itself.
如果您不使用memcached之类的东西,而是使用简单的 Dictionary
进程内对象缓存之类的东西,那么序列化和反序列化似乎是克隆对象的一种繁重方法.
If you aren't using something like memcached but rather using something like a simple Dictionary
in-process object cache then serializing and deserializing seems like a rather heavy approach to cloning objects though.
这篇关于System.Json.Net-反序列化Task< T>失败(没有无参数的构造函数)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!