Class SpeedLimiterService
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
contextnintThe pointer of the service context.
readByteslongHow many bytes consumed on current operation.
tokenCancellationTokenCancellation token for the async operation.
Returns
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
FreeServiceContext(nint)
Free the speed limiter service context.
public static void FreeServiceContext(nint context)
Parameters
contextnint