System.Progress

作者:追风剑情 发布于:2024-1-22 15:36 分类:C#

[官方文档] Progress<T> 类

在上下文(SynchronizationContext)中调用进度报告事件。即内部调用的是 m_synchronizationContext.Post() 方法。

  1. using System;
  2. using System.Threading.Tasks;
  3.  
  4. namespace ConsoleApp11
  5. {
  6. internal class Program
  7. {
  8. static void Main(string[] args)
  9. {
  10. Progress<int> progress = new Progress<int>((value) => {
  11. Console.WriteLine("进度 {0}", value);
  12. });
  13.  
  14. Task<int> task = Calculate(progress);
  15. int sum = task.Result;
  16. Console.WriteLine("sum={0}", sum);
  17.  
  18. Console.ReadKey();
  19. }
  20.  
  21. public static async Task<int> Calculate(IProgress<int> progress)
  22. {
  23. int sum = 0;
  24. for(int i=0; i< 10; i++)
  25. {
  26. await Task.Delay(1000);
  27. sum += i;
  28. progress.Report(i);
  29. }
  30. return sum;
  31. }
  32. }
  33. }

运行测试

1111111.png


标签: C#

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号