Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
2.5 kB
1
Indexable
Never
using System;
using System.Collections.Concurrent;
using System.Threading;
using System.Threading.Tasks;

class Program
{
    static ConcurrentQueue<string> dataQueue = new ConcurrentQueue<string>();
    static object consumerLock = new object();
    static event Action<string> DataProduced;
    static int dataId = 0;
    static DateTime writingStartTime;

    static void Main(string[] args)
    {
        var producerThread = new Thread(ProducerThread);
        producerThread.Start();

        DataProduced += ConsumerMethod;

        Console.WriteLine("Press Enter to stop the program.");
        Console.ReadLine();

        producerThread.Join();
    }

    static void ProducerThread()
    {
        var random = new Random();
        while (true)
        {
            var dateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            var uintValue = (uint)random.Next();
            var ushortValue = (ushort)random.Next();
            var intValue = random.Next();
            var shortValue = (short)random.Next();
            var int32Value = random.Next();

            var data = $"{dateTime},{uintValue},{ushortValue},{intValue},{shortValue},{int32Value}";
            DataProduced?.Invoke(data);

            Thread.Sleep(50000); // Sleep for 50 seconds
        }
    }

    static void ConsumerMethod(string data)
    {
        lock (consumerLock)
        {
            var id = Interlocked.Increment(ref dataId);
            dataQueue.Enqueue($"{id},{data}");
            Console.WriteLine($"Data with ID {id} added to the queue.");
        }

        if (dataId == 1)
            writingStartTime = DateTime.Now;

        Task.Run(() => WriteDataToCSV());
    }

    static void WriteDataToCSV()
    {
        lock (consumerLock)
        {
            using (var writer = new System.IO.StreamWriter("data.csv", true))
            {
                while (dataQueue.TryDequeue(out var data))
                {
                    writer.WriteLine(data);
                    var parts = data.Split(',');
                    var dateTime = parts[1];
                    var uintValue = parts[2];
                    var ushortValue = parts[3];
                    var intValue = parts[4];
                    var shortValue = parts[5];
                    var int32Value = parts[6];

                    Console.WriteLine($"Data: DateTime={dateTime}, UInt={uintValue}, UShort={ushortValue}, Int={intValue}, Short={shortValue}, Int32={int32Value}");
                }
            }
        }
    }
}