123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657 |
- using Microsoft.Extensions.Hosting;
- using Microsoft.Extensions.Logging;
- using System;
- using System.IO;
- using System.Threading;
- using System.Threading.Tasks;
- using System.Threading.Tasks.Dataflow;
- namespace ActionBlockTest
- {
- public class Worker : BackgroundService
- {
- private readonly ILogger<Worker> _logger;
- private ActionBlock<int> actionBlock;
- public Worker(ILogger<Worker> logger)
- {
- _logger = logger;
- }
- public override Task StartAsync(CancellationToken cancellationToken)
- {
- FileStream fileStream = new FileStream("./test.txt", FileMode.OpenOrCreate);
- fileStream.Seek(0, SeekOrigin.Current);
- StreamWriter streamWriter = new StreamWriter(fileStream);
- for (int i = 0; i < 2000; i++)
- {
- streamWriter.WriteLine("{\"seq\": \"" + i + "\",\"camName\": \"¿ØÖÆÊÒ_Ïñ»ú1_ǹ»ú\",\"presetCode\": \"1\"},");
- }
- streamWriter.Flush();
- streamWriter.Close();
- actionBlock = new ActionBlock<int>(
- async e => { Task.Delay(1000).Wait(); Console.WriteLine(e); },
- new ExecutionDataflowBlockOptions()
- { MaxDegreeOfParallelism = 1, MaxMessagesPerTask = 10 }
- );
- return base.StartAsync(cancellationToken);
- }
- protected override async Task ExecuteAsync(CancellationToken stoppingToken)
- {
- int index = 0;
- while (!stoppingToken.IsCancellationRequested)
- {
- //_logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
- actionBlock.Post(index++);
- MemoryStream memoryStream = new MemoryStream();
- StreamWriter streamWriter = new StreamWriter(memoryStream);
- await Task.Delay(10, stoppingToken);
- }
- }
- }
- }
|