Use WaitCallback to run thread in Thread Pool - CSharp Thread Asynchronous

CSharp examples for Thread Asynchronous:Thread

Description

Use WaitCallback to run thread in Thread Pool

Demo Code

using System;/*  w  ww . ja  va2 s  . com*/
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;
      for (int i = 0; i < logFilesAmount; i++)
      {
         var logManager = new LogManager($"log-{i + 1}.txt");
         ThreadPool.QueueUserWorkItem(new WaitCallback((o) => { logManager.Generate(); }));
      }
      Console.WriteLine("Files written");
   }
}

Result


Related Tutorials