© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•3y ago•
1 reply
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.
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

Block of code
C#CC# / help
3y ago
method are not stored in object but can be called from object?
C#CC# / help
12mo ago
Object Method error
C#CC# / help
3y ago