Run thread with Task - CSharp Thread Asynchronous

CSharp examples for Thread Asynchronous:Task

Description

Run thread with Task

Demo Code

using System;//from   ww w .  j a  va  2 s .  com
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.Text;
using System.IO;
class Program
{
   static void Main(string[] args)
   {
      int tasksAmount = 10;
      Task[] tasks = new Task[tasksAmount];
      Console.WriteLine("Writing tasks started");
      for(int i=0; i<tasksAmount; i++)
      {
         string fileName = $"log-{i + 1}.txt";
         int id = i + 1;
         tasks[i] = Task.Run(() =>
         {
            Console.WriteLine($"Task {id} running on thread: {Thread.CurrentThread.ManagedThreadId} / writing file {fileName}");
            var generator = new ReportGenerator(fileName);
            generator.Generate();
         });
      }
      Task.WaitAll(tasks);
      Console.WriteLine("Writing tasks finished");
   }
}
public class ReportGenerator
{
   public string FileName;
   public ReportGenerator(string fileName)
   {
      FileName = fileName;
   }
   public void Generate()
   {
      FileStream stream = File.OpenWrite(FileName);
      using (StreamWriter writer = new StreamWriter(stream))
      {
         for (int i = 0; i < 100000; i++)
         {
            writer.WriteLine($"Line {i}");
         }
      }
   }
}

Result


Related Tutorials