mrT
mrT

Reputation: 86

FileSystemWatcher with other Methods Executing at the Same Time

I am writing a program that has a FileSystemWatcher. I also have two other methods that I want to run alongside the FSW. But my other methods don't get executed because the program is always at the FSW.

Essentially, I want to have the FileSystemWatcher keep going and be able to perform other actions in my program at the same time.

How can I structure my code to achieve this?

Currently, my code has this structure:

namespace MyApp
{
 class Program
 {
   static void Main(string[] args)
   {
     // call the FSW
     MyFileSystemWatcher(path);

     // call another method
     AnotherMethod1();  

     // call another method
     AnotherMethod2();
   }

   //----- file system watcher methods -----//

   private static void MyFileSystemWatcher(string path)
   {
     // code for the file system watcher
    FileSystemWatcher fileSystemWatcher = new FileSystemWatcher();
    fileSystemWatcher.Path = path;
    fileSystemWatcher.Created += FileSystemWatcher_Created;
    fileSystemWatcher.Renamed += FileSystemWatcher_Renamed;
    fileSystemWatcher.Deleted += FileSystemWatcher_Deleted;
    fileSystemWatcher.EnableRaisingEvents = true; 
   }

   private static void FileSystemWatcher_Created(object sender, FileSystemEventArgs e)
   {
        Console.WriteLine("File created: {0}", e.Name);
   }

   private static void FileSystemWatcher_Renamed(object sender, FileSystemEventArgs e)
   {
        Console.WriteLine("File renamed: {0}", e.Name);
   }

   private static void FileSystemWatcher_Deleted(object sender, FileSystemEventArgs e)
   {
        Console.WriteLine("File deleted: {0}", e.Name);
   }

   //----- end of file system watcher methods -----//

   //----- other methods in the program -----//

   public static void AnotherMethod1()
   {
    // code for Method1
   }

   private static void AnotherMethod2()
   {
    // code for Method2
   }

 }

}

Thank you.

Upvotes: 0

Views: 426

Answers (1)

Derviş Kayımbaşıoğlu
Derviş Kayımbaşıoğlu

Reputation: 30663

Make your method async

private static async Task MyFileSystemWatcher(string path)
{
    // code for the file system watcher
}

then

 static void Main(string[] args)
 {
   // call the File System Watcher
   var task = MyFileSystemWatcher(path);

   // call another method
   AnotherMethod1();  

   // call another method
   AnotherMethod2();
 }

Alternatively, If you dont want to touch your method (not preferable), then

var task = Task.Run(() => MyFileSystemWatcher(path));

Upvotes: 1

Related Questions