Worker.cs 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. using Microsoft.Extensions.Hosting;
  2. using Microsoft.Extensions.Logging;
  3. using System;
  4. using System.IO;
  5. using System.Threading;
  6. using System.Threading.Tasks;
  7. using System.Threading.Tasks.Dataflow;
  8. namespace ActionBlockTest
  9. {
  10. public class Worker : BackgroundService
  11. {
  12. private readonly ILogger<Worker> _logger;
  13. private ActionBlock<int> actionBlock;
  14. public Worker(ILogger<Worker> logger)
  15. {
  16. _logger = logger;
  17. }
  18. public override Task StartAsync(CancellationToken cancellationToken)
  19. {
  20. FileStream fileStream = new FileStream("./test.txt", FileMode.OpenOrCreate);
  21. fileStream.Seek(0, SeekOrigin.Current);
  22. StreamWriter streamWriter = new StreamWriter(fileStream);
  23. for (int i = 0; i < 2000; i++)
  24. {
  25. streamWriter.WriteLine("{\"seq\": \"" + i + "\",\"camName\": \"¿ØÖÆÊÒ_Ïñ»ú1_ǹ»ú\",\"presetCode\": \"1\"},");
  26. }
  27. streamWriter.Flush();
  28. streamWriter.Close();
  29. actionBlock = new ActionBlock<int>(
  30. async e => { Task.Delay(1000).Wait(); Console.WriteLine(e); },
  31. new ExecutionDataflowBlockOptions()
  32. { MaxDegreeOfParallelism = 1, MaxMessagesPerTask = 10 }
  33. );
  34. return base.StartAsync(cancellationToken);
  35. }
  36. protected override async Task ExecuteAsync(CancellationToken stoppingToken)
  37. {
  38. int index = 0;
  39. while (!stoppingToken.IsCancellationRequested)
  40. {
  41. //_logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
  42. actionBlock.Post(index++);
  43. MemoryStream memoryStream = new MemoryStream();
  44. StreamWriter streamWriter = new StreamWriter(memoryStream);
  45. await Task.Delay(10, stoppingToken);
  46. }
  47. }
  48. }
  49. }