Table of Contents

Class SpeedLimiterService

Namespace
Hi3Helper.Plugin.Core.Utility
Assembly
Hi3Helper.Plugin.Core.dll

Provides a helper for using Speed Limiter Service.

public static class SpeedLimiterService
Inheritance
SpeedLimiterService
Inherited Members

Remarks

In order to use the service, make sure the main application has registered the service's callback using RegisterSpeedThrottlerService export API. Once the service is successfully registered, you can call AddBytesOrWaitAsync(nint, long, CancellationToken) method to pass the read bytes to the service and then throttle the speed for you.

Usage example on your code:

async Task ReadDataAsync(Stream inputStream, Stream outputStream, CancellationToken token)
{
    byte[] buffer = new byte[8192];
    int read;

    nint context = SpeedLimiterService.CreateServiceContext();
    while ((read = await inputStream.ReadAsync(buffer, 0, buffer.Length, token)) > 0)
    {
        // Do anything...
        ...

        // Pass the read bytes to the speed limiter service, and wait if necessary until the service allows more bytes to be processed.
        await SpeedLimiterService.AddBytesOrWaitAsync(context, read, token);
    }
}

Methods

AddBytesOrWaitAsync(nint, long, CancellationToken)

Adds-up counter of the consumed bytes into the service, and await (throttle) if the target speed is already reached.
If the service is not registered or the callback is not set, this method will simply return immediately without awaiting.

public static ValueTask AddBytesOrWaitAsync(nint context, long readBytes, CancellationToken token = default)

Parameters

context nint

The pointer of the service context.

readBytes long

How many bytes consumed on current operation.

token CancellationToken

Cancellation token for the async operation.

Returns

ValueTask

CreateServiceContext()

Creates a context to be used for the speed limiter service. This context can be used into multiple instances or threads of your downloader.

public static nint CreateServiceContext()

Returns

nint

FreeServiceContext(nint)

Free the speed limiter service context.

public static void FreeServiceContext(nint context)

Parameters

context nint