Link to home
Start Free TrialLog in
Avatar of sitg
sitgFlag for Iceland

asked on

file accessing problem in multi threading

hi,

i have a asp.net application , when application starts a dedicated thread is started to check if a file is there. if not create it.

2. my aspx page do the appending on that file.
my process is quad core. when i start the application both the thread try to create and append simultanously. so file is used by another process problem is there.

can any
--------------------- in global .aspx-------------------------------
protected void Application_Start(Object sender, EventArgs e)
		{
            try
            {
                ThreadStart job = new ThreadStart(FileNameGenerator.CreateMove);
                Thread thread = new Thread(job);
                thread.Name = "Moniter_Log";
                thread.Start();
            }
            catch (Exception ex)
            {
            
                        }
 
		}
--------------
method being called in abovet thread-----------------
 public static void CreateMove()
{
     string FileName = path+DateTime.Now.ToString("dd_MM_yyyy_HH")+".txt";
 
     while (true)
     {
         try
         {
 
             String[] files = Directory.GetFiles(path);
             if (!File.Exists(FileName) && files.Length > 0)
             {
                 string oldPath = ConfigurationManager.AppSettings["FilePath2"];
                 foreach (string file in files)
                     File.Move(file, file.Replace(path, oldPath));
 
                 FileStream stream = new FileStream(FileName, FileMode.Append, FileAccess.ReadWrite,FileShare.Write);
                // File.Create(FileName);
 
             }
             else if (!File.Exists(FileName))
             {
                 FileStream stream = new FileStream(FileName, FileMode.Append, FileAccess.ReadWrite, FileShare.Write);
 
             }
         }
 
 
         catch (Exception ex)
         {
         }
         finally
         {
             Thread.Sleep(1000 * 60 * 1);
         }
     }
 }
-------------------------------------------------------------------
in aspx page
 protected void Page_Load(object sender, EventArgs e){
public void Write(string Text,string FileName)
        {
            while (!File.Exists(FileName))
                Thread.Sleep(200);
           lock(this)
           {
 
               FileStream stream = new FileStream(FileName, FileMode.Append, FileAccess.ReadWrite);
               StreamWriter writer = new StreamWriter(stream);
           //StreamWriter objStreamWriter1 = File.AppendText(FileName);
           writer.WriteLine(Text);
           writer.Close();
       }
       }}
 
-------------------------------------------------------------

Open in new window

Avatar of evilrix
evilrix
Flag of United Kingdom of Great Britain and Northern Ireland image

SOLUTION
Avatar of evilrix
evilrix
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of sitg

ASKER

hi evilrix:

it will be nice of you ,  if you give a fix of this code .
because i have very less time right now.

i will read on getting the time.

Thanx
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
The code below is a working example of how a mutex synchronizes threads. Without it the output is a mess. With it each thread outputs 10 lines and then defers to the other. To see the difference comment out the bits I've noted in the code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
 
 
namespace cs_console
{
    class Program
    {
        static bool bQuit = false;
        static Mutex mtx = new Mutex(false);
 
        static void ThreadFunc()
        {
            while (!bQuit)
            {
                for (int x = 0; x < 10; ++x)
                {
                    //////////////////////////////////////////////////
                    // Comment out to see what it's like with no mutex
                    mtx.WaitOne();
                    //////////////////////////////////////////////////
                    for (int y = 0; y < 10; ++y)
                    {
                        Console.WriteLine("In thread: " + y.ToString());
                        Thread.Sleep(0);
                    }
                    //////////////////////////////////////////////////
                    // Comment out to see what it's like with no mutex
                    mtx.ReleaseMutex();
                    //////////////////////////////////////////////////
                }
            }
        }
        static void Main(string[] args)
        {
            Thread thread = new Thread(new ThreadStart(Program.ThreadFunc));
            thread.Start();
 
            for (int x = 0; x < 10; ++x)
            {
                //////////////////////////////////////////////////
                // Comment out to see what it's like with no mutex
                mtx.WaitOne();
                //////////////////////////////////////////////////
                for (int y = 0; y < 10; ++y)
                {
                    Console.WriteLine("In main: " + y.ToString());
                    Thread.Sleep(0);
                }
                //////////////////////////////////////////////////
                // Comment out to see what it's like with no mutex
                mtx.ReleaseMutex();
                //////////////////////////////////////////////////
            }
 
            bQuit = true;
 
            thread.Join();
        }
    }
}

Open in new window

Avatar of sitg

ASKER

thanks,
but i have question.
if the both threads runs simultaneosly on two processors.

because if at same time both request for
  mtx.WaitOne();

will it work ...
Yes, only one will win and the other will block. This object is designed to be used in this way.
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
If you need to synchronize this is some way you can either create the mutex so the thread creating it has initial ownership or you can use an AutoResetEvent to synchronize this ion some way.

http://msdn2.microsoft.com/en-us/library/system.threading.autoresetevent.aspx
The following example uses 2 auto reset events to pass signals between main and thread. Comments in the code should clarify what is going on: -
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
 
 
namespace cs_console
{
    class Program
    {
        static bool bQuit = false;
        static Mutex mtx = new Mutex(false);
        static AutoResetEvent autoEventThread = new AutoResetEvent(false);
        static AutoResetEvent autoEventMain = new AutoResetEvent(false);
 
        static void ThreadFunc()
        {
            while (!bQuit)
            {
                for (int x = 0; x < 10; ++x)
                {
                    //////////////////////////////////////////////////////
                    // Wait for main to signal
                    autoEventThread.WaitOne();
                    //////////////////////////////////////////////////////
 
                    if (!bQuit)
                    {
                        //////////////////////////////////////////////////
                        // Comment out to see what it's like with no mutex
                        mtx.WaitOne();
                        //////////////////////////////////////////////////
                        for (int y = 0; y < 10; ++y)
                        {
                            Console.WriteLine("In thread: " + y.ToString());
                            Thread.Sleep(0);
                        }
                        //////////////////////////////////////////////////
                        // Comment out to see what it's like with no mutex
                        mtx.ReleaseMutex();
                        //////////////////////////////////////////////////
                        // Signal main
                        autoEventMain.Set();
                        //////////////////////////////////////////////////
                    }
                }
            }
        }
        static void Main(string[] args)
        {
            Thread thread = new Thread(new ThreadStart(Program.ThreadFunc));
            thread.Start();
 
            for (int x = 0; x < 10; ++x)
            {
                //////////////////////////////////////////////////
                // Use event to ensure main runs before thread
                // and do two main loops to one thread loop
                if ((x > 0) && (x % 2) == 0)
                {
                    // Signal thread
                    autoEventThread.Set();
                    // Wait for thread to signal
                    autoEventMain.WaitOne();
                }
                //////////////////////////////////////////////////
                // Comment out to see what it's like with no mutex
                mtx.WaitOne();
                //////////////////////////////////////////////////
                for (int y = 0; y < 10; ++y)
                {
                    Console.WriteLine("In main: " + y.ToString());
                    Thread.Sleep(0);
                }
                //////////////////////////////////////////////////
                // Comment out to see what it's like with no mutex
                mtx.ReleaseMutex();
                //////////////////////////////////////////////////
            }
 
            bQuit = true;
 
            //////////////////////////////////////////////////////
            // Signal thread
            autoEventThread.Set();
            //////////////////////////////////////////////////////
 
            thread.Join();
        }
    }
}

Open in new window

SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Hello sitg,

about the two processor question.

The definition of a thread is that it is a "subprocess" within a process that share memory with the other subprocesses. That way the address to the semaphore/mutex is the same in all threads within that process. Your quad cores also share cache physically which makes things fast and easy. Compare this to actually having 4 SIMD-coupled procs on a quad proc mother board.
Avatar of sitg

ASKER

evilrix:

it is not working i just  put the mutex object in the global.asax. which is visible to all.
and rest of the code as you given
put same file access problem is occuring. or safe handle has been closed problem