Skip to content

Reduce timer cpu load #78

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Sep 23, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 19 additions & 9 deletions Thirdweb/Thirdweb.Utils/ThirdwebTask.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
using System.Diagnostics;

namespace Thirdweb;

public static class ThirdwebTask
Expand All @@ -11,26 +13,34 @@ public static class ThirdwebTask
public static async Task Delay(int millisecondsDelay, CancellationToken cancellationToken = default)
{
var startTime = DateTime.UtcNow;
while ((DateTime.UtcNow - startTime).TotalMilliseconds < millisecondsDelay && !cancellationToken.IsCancellationRequested)
var endTime = startTime.AddMilliseconds(millisecondsDelay);
var currentDelay = 10;

while (DateTime.UtcNow < endTime && !cancellationToken.IsCancellationRequested)
{
// Yield to avoid blocking the main thread, especially in WebGL
await Task.Yield();
await MinimalDelay(currentDelay);

// Introduce a minimal delay to check again
await MinimalDelay(10);
if (DateTime.UtcNow.AddMilliseconds(currentDelay) < endTime)
{
currentDelay = Math.Min(currentDelay * 2, 100);
}
else
{
currentDelay = (int)(endTime - DateTime.UtcNow).TotalMilliseconds;
}
}
}

/// <summary>
/// Provides a minimal delay by looping for a specified number of milliseconds.
/// Provides a minimal delay using a manual loop with short sleeps to reduce CPU usage.
/// </summary>
/// <param name="milliseconds">The number of milliseconds to delay.</param>
/// <returns>A task that completes after the specified minimal delay.</returns>
private static async Task MinimalDelay(int milliseconds)
{
var startTime = DateTime.UtcNow;
while ((DateTime.UtcNow - startTime).TotalMilliseconds < milliseconds)
var stopwatch = Stopwatch.StartNew();
while (stopwatch.ElapsedMilliseconds < milliseconds)
{
Thread.Sleep(1);
await Task.Yield();
}
}
Expand Down
Loading