stackoverflow1453

Programming&&Games&&Life

Archive for July, 2016

Lock ing an object

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;

namespace lockOrnek2
{
    class Program
    {
        //create locking object    
        static object _kontrol = new object();

        static void say1()
        {
            lock (_kontrol)
            {

                for (int i = 0; i < 20; i++)
                {
                    Console.WriteLine(i + " - x");
                }
            }
        }

        static void say2()
        {
            lock (_kontrol)
            {
                for (int i = 0; i < 20; i++)
                {
                    Console.WriteLine(i + " - y");
                }
            }
        }

        static void Main(string[] args)
        {
            Thread t1 = new Thread(new ThreadStart(say1));
            Thread t2 = new Thread(new ThreadStart(say2));
            t1.Start();
            t2.Start();
        }
    }
}

Mutithreading – Lock a file

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

namespace LockOrnek
{
    class Program
    {
        string yol = @"C:\Users\dsadas\Desktop\veri.txt";

        void Yaz()
        {
            lock (yol)
            {
                //flush file before writing
                File.WriteAllText(yol, string.Empty);

                StreamWriter yaz = File.AppendText(yol);

                for (int i = 0; i < 10; i++)
                {
                    Thread.Sleep(100);
                    yaz.WriteLine(Environment.TickCount);
                    Console.WriteLine("Writing");
                }
                yaz.Close();
            }
        }

        void Oku()
        {
            lock (yol)
            {
                var yazi = String.Empty;
                StreamReader oku = File.OpenText(yol);

                while ((yazi = oku.ReadLine()) != null)
                {
                    Console.WriteLine("Reading");
                }

                oku.Close();
            }
        }

        static void Main(string[] args)
        {
            Program a = new Program();

            Thread t1 = new Thread(new ThreadStart(a.Yaz));
            t1.Start();
            Thread t2 = new Thread(new ThreadStart(a.Oku));
            t2.Start();

            Console.ReadLine();
        }
    }
}