Counter.razor 752 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. @page "/counter"
  2. @rendermode InteractiveServer
  3. @using System.Threading
  4. <PageTitle>Counter</PageTitle>
  5. <h1>Counter</h1>
  6. <p role="status">Current count: @currentCount</p>
  7. <button class="btn btn-primary" @onclick="IncrementCount">Click me</button>
  8. @* @if (currentCount % 2 == 0)
  9. {
  10. <p>You win!</p>
  11. } *@
  12. @code {
  13. private static int currentCount = 0;
  14. private void IncrementCount()
  15. {
  16. // 启动后台任务进行计数
  17. _ = Task.Run(async () =>
  18. {
  19. while (true)
  20. {
  21. await Task.Delay(1000);
  22. currentCount++;
  23. await InvokeAsync(() =>
  24. {
  25. StateHasChanged();
  26. });
  27. }
  28. });
  29. }
  30. }