-
-
Save noseratio/73f6cd2fb328387ace2a7761f0b0dadc to your computer and use it in GitHub Desktop.
Timing setTimeout vs Task.Yield in Blazor
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@* https://stackoverflow.com/q/70091469/1768303 *@ | |
@inject IJSRuntime JS | |
<p>@progress</p> | |
<p>setTimeout: @result1</p> | |
<p>Task.Yield: @result2</p> | |
@code | |
{ | |
string progress = "please wait..."; | |
string result1 = "?"; | |
string result2 = "?"; | |
protected override void OnAfterRender(bool firstRender) | |
{ | |
if (firstRender) RunAsync(); | |
} | |
const string SCRIPT = @"({ | |
test: async n => { | |
for (i = 0; i < n; i++) { | |
await new Promise(r => setTimeout(r, 0)); | |
} | |
} | |
})"; | |
async void RunAsync() | |
{ | |
const int iterations = 1000; | |
var jsTest = await JS.InvokeAsync<IJSInProcessObjectReference>("eval", SCRIPT); | |
// timeing await new Promise(r => setTimeout(r)) | |
var sw1 = System.Diagnostics.Stopwatch.StartNew(); | |
await jsTest.InvokeVoidAsync("test", iterations); | |
result1 = $"{sw1.ElapsedMilliseconds}ms"; | |
StateHasChanged(); | |
// timing await Task.Yield() | |
var sw2 = System.Diagnostics.Stopwatch.StartNew(); | |
for (int i = 0; i < iterations; i++) | |
{ | |
//await Yield(); | |
await Task.Yield(); | |
} | |
result2 = $"{sw2.ElapsedMilliseconds}ms"; | |
StateHasChanged(); | |
progress = String.Empty; | |
StateHasChanged(); | |
} | |
static Task Yield() | |
{ | |
var tcs = new TaskCompletionSource<bool>(); | |
System.Threading.ThreadPool.QueueUserWorkItem(_ => tcs.TrySetResult(true)); | |
return tcs.Task; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment