using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.IO;

namespace ThreadLibrary
{
   public class FileIO
   {
      Mutex m = new Mutex(false, "named mutex");
      //Mutex m = new Mutex();

      public void WriteToFile()
      {
         try
         {
            m.WaitOne();

            FileStream fs = new FileStream("sync.txt", FileMode.Append);

            StreamWriter sw = new StreamWriter(fs);

            for (int i = 1; i < 10000000; i++)
            {
               sw.WriteLine(Thread.CurrentThread.Name);
            }

            sw.Flush();
            sw.Close();
            fs.Close();

            Console.WriteLine(Thread.CurrentThread.Name + " fertig!");
            m.ReleaseMutex();
         }
         catch (AbandonedMutexException ame)
         {
            if (ame.Mutex != null)
               ame.Mutex.ReleaseMutex();
         }
         catch (IOException e)
         {
            Console.WriteLine(e.ToString());
         }
      }
   }
}