Skip to content

Commit 6737994

Browse files
authored
Reduce timer cpu load (#78)
1 parent 7e8493a commit 6737994

File tree

1 file changed

+19
-9
lines changed

1 file changed

+19
-9
lines changed

Thirdweb/Thirdweb.Utils/ThirdwebTask.cs

+19-9
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
using System.Diagnostics;
2+
13
namespace Thirdweb;
24

35
public static class ThirdwebTask
@@ -11,26 +13,34 @@ public static class ThirdwebTask
1113
public static async Task Delay(int millisecondsDelay, CancellationToken cancellationToken = default)
1214
{
1315
var startTime = DateTime.UtcNow;
14-
while ((DateTime.UtcNow - startTime).TotalMilliseconds < millisecondsDelay && !cancellationToken.IsCancellationRequested)
16+
var endTime = startTime.AddMilliseconds(millisecondsDelay);
17+
var currentDelay = 10;
18+
19+
while (DateTime.UtcNow < endTime && !cancellationToken.IsCancellationRequested)
1520
{
16-
// Yield to avoid blocking the main thread, especially in WebGL
17-
await Task.Yield();
21+
await MinimalDelay(currentDelay);
1822

19-
// Introduce a minimal delay to check again
20-
await MinimalDelay(10);
23+
if (DateTime.UtcNow.AddMilliseconds(currentDelay) < endTime)
24+
{
25+
currentDelay = Math.Min(currentDelay * 2, 100);
26+
}
27+
else
28+
{
29+
currentDelay = (int)(endTime - DateTime.UtcNow).TotalMilliseconds;
30+
}
2131
}
2232
}
2333

2434
/// <summary>
25-
/// Provides a minimal delay by looping for a specified number of milliseconds.
35+
/// Provides a minimal delay using a manual loop with short sleeps to reduce CPU usage.
2636
/// </summary>
2737
/// <param name="milliseconds">The number of milliseconds to delay.</param>
28-
/// <returns>A task that completes after the specified minimal delay.</returns>
2938
private static async Task MinimalDelay(int milliseconds)
3039
{
31-
var startTime = DateTime.UtcNow;
32-
while ((DateTime.UtcNow - startTime).TotalMilliseconds < milliseconds)
40+
var stopwatch = Stopwatch.StartNew();
41+
while (stopwatch.ElapsedMilliseconds < milliseconds)
3342
{
43+
Thread.Sleep(1);
3444
await Task.Yield();
3545
}
3646
}

0 commit comments

Comments
 (0)