user726720
user726720

Reputation: 1247

Locking and synchronization

I'm having a hard time figuring out the problem with the following code:

public void InitList(object source, FileSystemEventArgs f)
{
    if (!Monitor.TryEnter(lockObject))
    {
        Monitor.Exit(lockObject);
        return;
    }
    try
    {
        /// do something
    }
    catch (Exception e)
    {
        MessageBox.Show("The Process Failed:" + e.ToString());
    }
    finally
    {
        Monitor.Exit(lockObject);

        _watcher.Path = textBox2.Text;

        _watcher.EnableRaisingEvents = true;
    }
}

I do have FileStreams, but I'm closing those properly. and I believe those are not the issue.

When I run the program first time, it goes to the catch with the exception: File cannot be accessed. With the second file copied to the directory, it gives me: object synchronization method was called from an unsynchronized block of code. This exception is given on monitor.exit(lockobject).

Rough IDEA about my program, and what I'm trying achieve:

There is a FileSystemWatcher running, when it picks up the file changed I process this file and report it on the UI (ListBox). Can you explain what could be causing the exception I am seeing?

Upvotes: 0

Views: 88

Answers (1)

flindeberg
flindeberg

Reputation: 5027

You have missunderstood what Monitor.TryEnter(obj) does, if it returns false you do not have to exit again, because you never entered!

Usually you use Monitor like this:

void MyMethod() {
  if (Monitor.TryEnter(lockObj)) {
    // Do stuff
    // Release lock
    Monitor.Exit(lockObj);
  } else {
    // We didn't get a lock, crash? Log? 
  }
}

Given the exception you are getting it might be that a delay is needed though, I've encountered issues where the filesystemwatcher fired events before the "offending" application had closed its stream, ie a collision in having the file open. There is no "general" rule of thumb on how long the delay have to be, but aim for something higher than the disk latency, especially for network drives! Ie on an SSD you might get away with 10 ms whilst closer to 100 ms might be needed for networked hard drives.

Upvotes: 1

Related Questions