Repository: dotnet/runtime
File: src/mono/wasm/Wasm.Build.Tests/Blazor/EventPipeDiagnosticsTests.cs (C#)

Code before:

        return dictionary;
    }

    private void UpdateCounterPage()
    {
        UpdateFile(Path.Combine("Pages", "Counter.razor"), new Dictionary<string, string> {
                {
                    @"currentCount++;",
                    """
                    for(int i = 0; i < 100; i++)
                    {
                        var sb = new System.Text.StringBuilder();
                        sb.Append("Incrementing count: ");
                        sb.Append(i);
                        sb.Append(" ");
                        sb.Append(DateTime.Now.ToString("O"));
                        if( i % 50 == 0)
                        {
                            Console.WriteLine(sb.ToString());
                        }
                    }
                    currentCount++;
                    if (currentCount > 4)
                    {
                        await Task.Delay(500); // Ensure the upload has time to start before we exit
                        Console.WriteLine("WASM EXIT 0");
                    }
                    """
                }
            });
    }

    private async Task SetupCounterPage(IPage page)
    {
        await Task.Delay(500);
        // Navigate to the Counter page
        await page.Locator("text=Counter").ClickAsync();

        // Verify we're on the Counter page
        var txt = await page.Locator("p[role='status']").InnerHTMLAsync();
        Assert.Equal("Current count: 0", txt);

        var up = """
        globalThis.uploadTrace = async (filename, tracesPromise) => {
            console.log(`${filename} typeof  ${typeof tracesPromise} ${new Date().toISOString()}`);

            const traces = await tracesPromise;

            console.log(`${filename} typeof  ${typeof traces} ${new Date().toISOString()}`);
                    

Review comment (refactor):
Magic number: The 500ms delay is hardcoded without explanation of why this specific duration was chosen. Consider extracting this to a named constant (e.g., `const int DiagnosticUploadDelayMs = 500`) with a comment explaining the rationale for this timing value, or using a more robust synchronization mechanism if possible.

Code after:
                        }
                    }
                    currentCount++;
                    """
                }
            });
    }

    private async Task SetupCounterPage(IPage page, string fileName, string traceCommand)
    {
        await Task.Delay(500);
        // Navigate to the Counter page
        await page.Locator("text=Counter").ClickAsync();

        // Verify we're on the Counter page
        var txt = await page.Locator("p[role='status']").InnerHTMLAsync();
        Assert.Equal("Current count: 0", txt);

        var up = """
        globalThis.collectAndUpload = async () => {
            console.log(`Tracing ${filename} started ${new Date().toISOString()}`);
            
            const traces = await ${traceCommand};

            console.log(`Tracing done ${new Date().toISOString()}`);
                    
            // concatenate the buffers into a single Uint8Array
            const concatenated = new Uint8Array(traces.reduce((acc, curr) => acc + curr.byteLength, 0));
            let offset = 0;
            for (const trace of traces) {
                concatenated.set(new Uint8Array(trace), offset);
                offset += trace.byteLength;
            }

            console.log(`File ${filename} size to upload: ${concatenated.byteLength} bytes ${new Date().toISOString()}`);
            await fetch(`/upload/${filename}`, {
                headers: {
                    'Content-Type': 'application/octet-stream'
                },
                method: 'POST',
                body: concatenated
            });
            console.log(`File uploaded successfully: ${new Date().toISOString()}`);
            await new Promise(resolve => setTimeout(resolve, 1000));
            console.log(`Shutting down: ${new Date().toISOString()}`);
            console.log(`WASM EXIT 0`);
        };
        console.log(`globalThis.collectAndUpload method created ${new Date().toISOString()}`);
        """;
        up = up.Replace("${traceCommand}", traceCommand).Replace("${filename}", fileName);
        await page.EvaluateAsync(up);