Skip to content

Enhance Json Serialize() with CancellationToken #611

@iSazonov

Description

@iSazonov

Scenario: PowerShell ConvertTo-Json cmdlet uses custom code (based on Netonsoft Json.NET) to serialize objects to Json. On every step it checks CancellationToken. Since PowerShell do all work in separate threads (runspaces) users from console or hosted application can gracefully stop the serialization process at any time.

While working on migrating the cmdlet on new Core Json API I discovered that System.Text.Json.JsonSerializer.Serialize() method has not a parameter for CancellationToken so unable to complete the migration.
Using SerializeAsync() looks too expensive for the task.

API proposal

namespace System.Text.Json
{
    public static partial class JsonSerializer
    {
        public static void Serialize<TValue>(Utf8JsonWriter writer, TValue value, JsonSerializerOptions options = null);    // Existing
        public static void Serialize<TValue>(Utf8JsonWriter writer, TValue value, JsonSerializerOptions options = null, CancellationToken cancellationToken = default);    // New
        public static void Serialize(Utf8JsonWriter writer, object value, Type inputType, JsonSerializerOptions options = null);    // Existing
        public static void Serialize(Utf8JsonWriter writer, object value, Type inputType, JsonSerializerOptions options = null, CancellationToken cancellationToken = default);    // New
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions