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.
Regarding performance...
I'm using the async/await pattern to call the DB (the whole app is async).
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":
- If Task is in my cache, await it and return the result.
- Otherwise, call the DB method without awaiting it and add the resultant task to the cache
When I add serialization, then the deserialization of the task:
Task<TItem>? cachedItem = JsonSerializer.Deserialize<Task<TItem>>(serializedItem);
results in
Deserialization of types without a parameterless constructor, a singular parameterized constructor, or a parameterized constructor annotated with 'JsonConstructorAttribute' is not supported.