Open M-Yankov opened 4 months ago
Second approach (modern) using async foreach ...
:
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
public class DataFiller
{
public async IAsyncEnumerable<int> FillDataAsync(int count)
{
Random random = new Random();
for (int i = 0; i < count; i++)
{
await Task.Delay(100); // Simulate some delay
yield return random.Next(1, 100); // Yield data asynchronously
}
}
}
public class DataProcessor
{
public async Task ProcessDataAsync(IAsyncEnumerable<int> dataStream)
{
int sum = 0;
await foreach (var value in dataStream)
{
sum += value; // Process the data
Console.WriteLine($"Processed value: {value}, Current Sum: {sum}");
}
}
}
public class Program
{
public static async Task Main(string[] args)
{
DataFiller filler = new DataFiller();
DataProcessor processor = new DataProcessor();
IAsyncEnumerable<int> dataStream = filler.FillDataAsync(10); // Fill 10 items asynchronously
await processor.ProcessDataAsync(dataStream); // Process the data asynchronously
}
}
Adding top priority it should be done ASAP, before project grows up
The application have 3 main loops:
The example below suggest a solution for non blocking thread (safe-thread) showing last two steps separated in classes using concurrent Queue. (Code samples are generated from Open AI ⚠️ )
Processor:
program.cs