1
+ using System . Diagnostics ;
2
+
1
3
namespace Thirdweb ;
2
4
3
5
public static class ThirdwebTask
@@ -11,26 +13,34 @@ public static class ThirdwebTask
11
13
public static async Task Delay ( int millisecondsDelay , CancellationToken cancellationToken = default )
12
14
{
13
15
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 )
15
20
{
16
- // Yield to avoid blocking the main thread, especially in WebGL
17
- await Task . Yield ( ) ;
21
+ await MinimalDelay ( currentDelay ) ;
18
22
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
+ }
21
31
}
22
32
}
23
33
24
34
/// <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 .
26
36
/// </summary>
27
37
/// <param name="milliseconds">The number of milliseconds to delay.</param>
28
- /// <returns>A task that completes after the specified minimal delay.</returns>
29
38
private static async Task MinimalDelay ( int milliseconds )
30
39
{
31
- var startTime = DateTime . UtcNow ;
32
- while ( ( DateTime . UtcNow - startTime ) . TotalMilliseconds < milliseconds )
40
+ var stopwatch = Stopwatch . StartNew ( ) ;
41
+ while ( stopwatch . ElapsedMilliseconds < milliseconds )
33
42
{
43
+ Thread . Sleep ( 1 ) ;
34
44
await Task . Yield ( ) ;
35
45
}
36
46
}
0 commit comments