views:

476

answers:

2

I am developing a database file system.It includes a multi-directory watcher which is a windows service and which uses the file system watcher class from .net.

I want to run each watcher class on separate thread.Thread can not be extended in .net because as it is "Sealed". What I want is, run all the methods of my watcher class in the related thread. How can I achieve this?

EDIT -

Following is my base watcher class.

 public abstract class WatcherBase
  {
    private IWatchObject _watchObject;

    public WatcherBase() { }

    public WatcherBase(IWatchObject watchObject, bool canPauseAndContinue)
    {
        _watchObject = watchObject;
        CanPauseAndContinue = canPauseAndContinue;
    }

    public bool CanPauseAndContinue { get; set; }

    public IWatchObject ObjectToWatch
    {
        get
        { 
            return _watchObject; 
        }
    }

    public abstract void Start();
    public abstract void Pause();
    public abstract void Continue();
    public abstract void Stop();
}

Following is my directory watcher class extended from the WatcherBase class

  namespace RankFs.WatcherService
  {
    public class DirectoryWatcher : WatcherBase
    {
    private WatchDirectory _directoryToWatch;
    private FileSystemWatcher _watcher;

    public DirectoryWatcher(WatchDirectory directory, bool CanPauseAndContinue)
        :base(directory ,CanPauseAndContinue)
    {
        _directoryToWatch = directory;
        _watcher = new FileSystemWatcher(_directoryToWatch.Path);
        _watcher.IncludeSubdirectories = _directoryToWatch.WatchSubDirectories;
        _watcher.Created +=new FileSystemEventHandler(Watcher_Created);
        //_watcher.Changed +=new FileSystemEventHandler(Watcher_Changed);
        _watcher.Deleted +=new FileSystemEventHandler(Watcher_Deleted);
        _watcher.Renamed +=new RenamedEventHandler(Watcher_Renamed);
    }

    public WatchDirectory DirectoryToWatch
    {
        get 
        {
            return _directoryToWatch;
        }
    }

    public override void Start()
    {
        _watcher.EnableRaisingEvents = true;
    }

    public override void Pause()
    {
        _watcher.EnableRaisingEvents = false;
    }

    public override void Continue()
    {
        _watcher.EnableRaisingEvents = true;
    }

    public override void Stop()
    {
        _watcher.EnableRaisingEvents = false;
    }

    private void Watcher_Created(object sender, FileSystemEventArgs e)
    {
       // adds a new file entry to database 
    }

    private void Watcher_Deleted(object sender, FileSystemEventArgs e)
    {
       //updates the database(deleted file)
    }

    private void Watcher_Renamed(object sender, RenamedEventArgs e)
    {
   //updates the database(renamed file)
    }
} }

I am stuck at this point.Please help me.

A: 

I would write a new class that wraps or adapts the FileSystemWatcher, and then launch my new class on a new thread. The adapter class will handle the notifications from the FSW class, and you can then work out the best way to broadcast or relay those notifications to some sort of marshalling function.

There are a few different ways to launch new threads and billions of tutorials on how to do it, so i'm not going to cover that here in this answer.

slugster
I have already done the "wrapping up" thing.And you are saying "launch new class on new thread".My question is the same.How to do that?I am stuck.
Ravi
+4  A: 

The FileSystemWatcher will trigger the events in a separate thread. The logic inside the event handlers will need to take that fact in consideration and perform any synchronization needed.

If you run the following example you will see that the Changed event handler will run in a different thread.

public static void Main(string[] args)
{
    Directory.CreateDirectory("dir1");
    Directory.CreateDirectory("dir2");
    Directory.CreateDirectory("dir3");

    Console.WriteLine("Main Thread Id: {0}", 
        Thread.CurrentThread.ManagedThreadId);

    const int watcherCount = 3;
    string[] dirs = new string[] { "dir1", "dir2", "dir3" };

    for (int i = 0; i < watcherCount; i++)
    {
        var watcher = new FileSystemWatcher();
        watcher.Path = dirs[i];
        watcher.Changed += (sender, e) =>
        {
            Console.WriteLine("File: {0} | Thread: {1}", e.Name,
                Thread.CurrentThread.ManagedThreadId);

            Thread.Sleep(2000); // Simulate long operation
        };
        watcher.EnableRaisingEvents = true;
    }

    File.WriteAllText(@"dir1\test1", "hello");
    File.WriteAllText(@"dir2\test2", "hello");
    File.WriteAllText(@"dir3\test3", "hello");

    Thread.Sleep(10000);
}

When running this sample I obtained the following output:

// Main Thread Id: 1
// File: test1 | Thread: 3
// File: test2 | Thread: 4
// File: test3 | Thread: 5
// File: test1 | Thread: 3
// File: test2 | Thread: 4
// File: test3 | Thread: 5

UPDATE: Since you are using the events approach in the FileSystemWatcher you are already using a multithreaded approach because the event handlers for each FileSystemWatcher instance will be triggered in a separate thread in an asynchronous way.

João Angelo
I couldn't get any idea about how to achieve multi threading.Can u please help more.I have edited my question and provided the code for reference.Have a look.
Ravi
@Ravi You don't need to do anything else to get your event handler methods to run on a separate thread
SpaceghostAli
This is the output which I got.'Main Thread Id 12File test Thread 13File test Thread 13'Still no multithreading.Why so?
Ravi
As you can see for yourself you have two different thread identifiers from the output. That means execution in two separate threads. What do you mean by no multithreading?
João Angelo
What I mean is,12 is main thread.But shouldn't be there 2 different thread for separate directory watcher.Like File test thread 13 File test thread 14??
Ravi
The sample code only writes a file to one of the directories (`File.WriteAllText(@"dir1\test", "hello");`). Write files to the other directories and you'll see the other threads. Also take in consideration that creating a file in a directory triggers the `Changed` event more than once.
João Angelo
Sorry if this is going annoying.But I have used them on different directories. | Directory.CreateDirectory("d:\\dir1"); Directory.CreateDirectory("d:\\dir2"); Directory.CreateDirectory("d:\\dir3");I really need help.M stuck here.
Ravi
I updated the sample code. I believe the previous was so simple that the same thread would be reused. I also add the output of a running the example in my machine.
João Angelo
yeah.I read abt same thread being reused on the msdn site before reading ur comment.U have got it.Thaks \m/ +1 + Acceptance
Ravi