C
C#6mo ago
pyrodistic

FileWatcher Mutex - Object synchronization method was called from an unsynchronized block of code.

The following code is an attempt at handling when multiple files are modified in the same folder. Since I'm doing database transactions on importer.DoImporterActionAsync, I need to make sure that it's handling files like a queue. I'm getting the error: 'Object synchronization method was called from an unsynchronized block of code.'. Even when copying a single file, and I'm not understanding why.
public async Task OnModifiedAsync(FileSystemEventArgs e)
{
if (e.FullPath.ToLower().EndsWith(extension_to_read))
{
string text = await CalculateSha256Async(e.FullPath);
if (file_hash != text)
{
file_hash = text;
Log.Information("File " + e.FullPath + " has been modified.");
Log.Information("Watching folder: " + folder);
await importer.DoImporterActionAsync(e.FullPath);
}
}
}

public async void OnModifiedAsyncHandler(object sender, FileSystemEventArgs e)
{
try
{
mutex.WaitOne();
await OnModifiedAsync(e);
}
finally
{
mutex.ReleaseMutex();
}
}
public async Task OnModifiedAsync(FileSystemEventArgs e)
{
if (e.FullPath.ToLower().EndsWith(extension_to_read))
{
string text = await CalculateSha256Async(e.FullPath);
if (file_hash != text)
{
file_hash = text;
Log.Information("File " + e.FullPath + " has been modified.");
Log.Information("Watching folder: " + folder);
await importer.DoImporterActionAsync(e.FullPath);
}
}
}

public async void OnModifiedAsyncHandler(object sender, FileSystemEventArgs e)
{
try
{
mutex.WaitOne();
await OnModifiedAsync(e);
}
finally
{
mutex.ReleaseMutex();
}
}
System.ApplicationException HResult=0x80131600 Message=Object synchronization method was called from an unsynchronized block of code. Source=System.Private.CoreLib StackTrace: at System.Threading.Mutex.ReleaseMutex() in /_/src/libraries/System.Private.CoreLib/src/System/Threading/Mutex.Windows.cs:line 92 at FileWatcherBase.<OnModifiedAsyncHandler>d__10.MoveNext() //...cut due to character limit.
1 Reply
Honza K.
Honza K.6mo ago
can you try to use semaphore slim instead of mutex? It could work for this