Showing posts with label Threading. Show all posts
Showing posts with label Threading. Show all posts

Tuesday, May 25, 2010

Using SortedList for FileWatcher

I need to do an update and archive files based on a condition in my application. So i have used sortedList to get all the files by processing the thread in my service. For details check my last post on this Multi Threading Using parameters for reference.

So I have updated on of my method DoTXT to achieve this from my previous post.

/// <summary>
        /// Thread 2, Displays that we are in thread 2
        /// </summary>
        public void DoTXT()
        {
            while (_stopThreads == false)
            {
                lock (this)
                {
                    // Write your TXT LOGIC HERE, Moving files and updating database etc
                    Console.WriteLine("Display Thread 2 " + strExt);
                    _threadOutput = "Hello Thread 2";
                    Thread.Sleep(1000);  // simulate a lot of processing
                    string[] Files = Directory.GetFiles("D://ThreadSample//Files//");
                    SortedList sList = new SortedList();
                    if (Files.Length > 0)
                    {
                        foreach (string s in Files)
                        {
                            try
                            {
                                if (Path.GetExtension(s).ToUpper().Equals(strExt))
                                {
                                    try
                                    {
                                        // if you date falls between two dates you need to change the condition while comparing.
                                        // Check the File class for rest of useful methods you require..File.GetLastAccessTime
                                        if (File.GetLastWriteTime(s).ToShortDateString().Equals(strDateTime))
                                        {
                                            DateTime dt = File.GetLastWriteTime(s);
                                            sList.Add(dt, Path.GetFullPath(s));
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        throw ex;
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                throw ex;
                            }
                        }
                        // Getting information from the SortedList.
                        foreach (string filename in sList.Values)
                        {
                            // Get all these file to zip for archive
                            Console.WriteLine("filename with sorted list." + filename);
                            // Do the db logic..
                        }
                    }
                    // we are in thread #2
                    Console.WriteLine("DoTXT Output --> {0}", _threadOutput + " datetime: -- > " + strDateTime);
                }
            }
        }

Multi Threading using Parameters

Recently i need write a file watcher. So i need to do based on the file types. I have written little bit of code for doing so. Here is the snippet of this.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.IO;
using System.Collections;
namespace ThreadSample
{
    class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            //
            // TODO: Add code to start application here
            // 
            DisplayThread objContainer1 = new DisplayThread(".TXT", DateTime.Now.ToShortDateString());
            Thread objThread1 = new Thread(new ThreadStart(objContainer1.DoTXT));
            objThread1.Start();
            DisplayThread objContainer2 = new DisplayThread(".PDF", DateTime.Now.ToShortDateString());
            Thread objThread2 = new Thread(new ThreadStart(objContainer2.DoPDF));
            objThread2.Start();
            Console.ReadLine();
        }
        
    }
    class DisplayThread
    {
        private bool _stopThreads = false;
        public bool StopThreads
        {
            set
            {
                _stopThreads = value;
            }
        }
        private string strExt, strDateTime = "";
        public DisplayThread(string Ext, string datetime)
        {
            strExt = Ext;
            strDateTime = datetime;
        }
        // shared memory variable between the two threads
        private string _threadOutput = "";
        /// <summary>
        /// Thread 1, Displays that we are in thread 1
        /// </summary>
        public void DoPDF( )
        {
            while (_stopThreads == false)
            {
                lock (this)
                {
                    // Write your PDF LOGIC HERE, Moving files and updating database etc
                    Console.WriteLine("Display Thread 1 " + strExt);
                    _threadOutput = "Hello Thread 1";
                    Thread.Sleep(1000);  // simulate a lot of processing
                    string[] Files = Directory.GetFiles("D://ThreadSample//Files//");
                    if (Files.Length > 0)
                    {
                        foreach (string s in Files)
                        {
                            try
                            {
                                if (Path.GetExtension(s).ToUpper().Equals(strExt))
                                {
                                    try
                                    {
                                        // if you date falls between two dates you need to change the condition while comparing.
                                        if (File.GetLastWriteTime(s).ToShortDateString().Equals(strDateTime))
                                        Console.WriteLine(s);
                                        // do the db logic and filemoving etc
                                    }
                                    catch (Exception ex)
                                    {
                                        throw ex;
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                throw ex;
                            }
                        }
                    }
                    // we are in thread #1
                    Console.WriteLine("DoPDF Output --> {0}", _threadOutput + " datetime: -- > " + strDateTime);
                }
            }
        }
        /// <summary>
        /// Thread 2, Displays that we are in thread 2
        /// </summary>
        public void DoTXT( )
        {
            while (_stopThreads == false)
            {
                lock (this)
                {
                    // Write your TXT LOGIC HERE, Moving files and updating database etc
                    Console.WriteLine("Display Thread 2 " + strExt);
                    _threadOutput = "Hello Thread 2";
                    Thread.Sleep(1000);  // simulate a lot of processing
                    string[] Files = Directory.GetFiles("D://ThreadSample//Files//");
                    if (Files.Length > 0)
                    {
                        foreach (string s in Files)
                        {
                            try
                            {
                                if (Path.GetExtension(s).ToUpper().Equals(strExt))
                                {
                                    try
                                    {
                                        // if you date falls between two dates you need to change the condition while comparing.
                                        // Check the File class for rest of useful methods you require..File.GetLastAccessTime
                                        if (File.GetLastWriteTime(s).ToShortDateString().Equals(strDateTime))
                                            Console.WriteLine(s);
                                        // do the db logic and filemoving etc
                                    }
                                    catch (Exception ex)
                                    {
                                        throw ex;
                                    }
                                }
                            }
                           
                            catch (Exception ex)
                            {
                                throw ex;
                            }
                        }
                       
                    }
                    // we are in thread #2
                    Console.WriteLine("DoTXT Output --> {0}", _threadOutput + " datetime: -- > " + strDateTime);
                }
            }
        }
    }
}


I need to check files based on the last modified date. so i am using File class to know the GetLastWriteTime. Instead you can also using System.IO.FileInfo to get the information of LastWriteTime.



string[] Files =  Directory.GetFiles("D://ThreadSample//Files//");
System.IO.FileInfo fileInfo = null;
if (Files.Length > 0)
 {
   foreach (string s in Files)
   {
     fileInfo = new System.IO.FileInfo(s);
      try
      {
        DateTime LastWT = fileInfo.LastWriteTime;
        Console.WriteLine("LastWrite Time" + LastWT.ToShortDateString());
       }
       catch (Exception ex)
       {
         throw ex;
       }
    }
}


Happy coding :-)