Insert to log file using Thread - CSharp Thread Asynchronous

CSharp examples for Thread Asynchronous:Thread

Description

Insert to log file using Thread

Demo Code

using System;/*from  w w  w .ja va 2 s  .c  o  m*/
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Threading;
public class LogManager
{
   public string FileName;
   public LogManager(string fileName)
   {
      FileName = fileName;
   }
   public void Generate()
   {
      using (StreamWriter writer = new StreamWriter(FileName))
      {
         for(int i=0; i<10000; i++)
         {
            writer.WriteLine($"Line {i + 1}");
         }
      }
   }
}
class Program
{
   static void Main(string[] args)
   {
      int logFilesAmount = 10;
      Thread[] threads = new Thread[logFilesAmount];
      Console.WriteLine("Starting writer threads...");
      for (int i=0; i<logFilesAmount; i++)
      {
         var logManager = new LogManager($"log-{i + 1}.txt");
         threads[i] = new Thread(logManager.Generate);
         threads[i].Start();
      }
      for(int i=0; i<logFilesAmount; i++)
      {
         threads[i].Join();
      }
      Console.WriteLine("All writer threads finished");
   }
}

Result


Related Tutorials