Search code examples
c#.netmultithreadingfilesystemwatcher

C# Raising an event in a .net assembly from a filesystemwatcher event handler


I am having an issue with cross thread communication in .net.

I created a .NET assembly that does not have a GUI front end. This assembly calls a FileSystemWatcher that monitors a specific folder for any files being newly created. When a file is created I want to be notified so that i can read the text from the file and then raise an event from my own object passing that data.

The issue that is occurring is that i get the following error when I try this.

"The calling thread cannot access this object because a different thread owns it"

Below is a summary of my program.

public void start()
{
    _IncomingWatcher = new FileSystemWatcher(strMessageInboundDir);
    _IncomingWatcher.Created += DataRecieved_Created;
    _IncomingWatcher.EnableRaisingEvents = true;
 }

-----------------------------------------------------------------------

private void DataRecieved_Created(object sender, FileSystemEventArgs e)
{
   var files = Directory.EnumerateFiles(strMessageInboundDir);
   foreach (string file in files)
   {

       var data = File.ReadAllText(file);
       data = ProcessMessageMCOINToADDN(data);

       if (DataRecieved != null)
       {
          MessageData tempmessage = new MessageData
          {
             MyEventString = data
          };
          DataRecieved?.Invoke(this, tempmessage);
       }
       File.Delete(file);
    }
}

any help would be greatly appreciated.

thanks J.W


Solution

  • You want the file or directory created, assuming its a file, the event args has the data you want.

    private void DataRecieved_Created(object sender, FileSystemEventArgs e)
    {
    
       if ( System.IO.File.Exists(e.FullPath )) // Might Be a Directory
       {
    
       var data = File.ReadAllText(e.FullPath);
       data = ProcessMessageMCOINToADDN(data);
    
       if (DataRecieved != null)
       {
          MessageData tempmessage = new MessageData
          {
             MyEventString = data
          };
          DataRecieved?.Invoke(this, tempmessage);
       }
        File.Delete(e.FullPath);
    
        }
    }
    

    More information on FileSystemEventArgs here:

    https://msdn.microsoft.com/en-us/library/system.io.filesystemeventargs(v=vs.110).aspx