© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•2y ago•
8 replies
Claudiu HBann

async/await and mutexes

I have a service that i will inject it as singleton that has:
    private readonly Dictionary<string, List<string>> _fromToAll = [];
    private readonly Mutex _mutex = new();
    private readonly Dictionary<string, List<string>> _fromToAll = [];
    private readonly Mutex _mutex = new();


and I want the dictionary to be lazy initialized only once when needed like:

    private async Task<Dictionary<string, List<string>>> FindFromToAll()
    {
        try
        {
            _mutex.WaitOne();
            if (_fromToAll.Count > 0)
            {
                return _fromToAll;
            }

            foreach (var serviceType in FindAllServiceTypes())
            {
                var service = ActivatorUtilities.CreateInstance(provider, serviceType);
                var fromTo = await service.Invoke<Task<List<string>>>("FromTo");
                _fromToAll.Add(serviceType.Name.Replace("Service", null), fromTo);
            }

            return _fromToAll;
        }
        finally
        {
            _mutex.ReleaseMutex();
        }
    }
    private async Task<Dictionary<string, List<string>>> FindFromToAll()
    {
        try
        {
            _mutex.WaitOne();
            if (_fromToAll.Count > 0)
            {
                return _fromToAll;
            }

            foreach (var serviceType in FindAllServiceTypes())
            {
                var service = ActivatorUtilities.CreateInstance(provider, serviceType);
                var fromTo = await service.Invoke<Task<List<string>>>("FromTo");
                _fromToAll.Add(serviceType.Name.Replace("Service", null), fromTo);
            }

            return _fromToAll;
        }
        finally
        {
            _mutex.ReleaseMutex();
        }
    }


but when I invoke and wait for the FromTo Task that returns a list of strings the context changes and when i release the mutex it crashes because i release it from an another thread, the exception message looks like this: "Object synchronization method was called from an unsynchronized block of code."
Even if i add ConfigureAwait(true) doesn't switch the context to the captured one.

Any idea why this happens or how can I do it differently?
Thank you in advance 😃
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,828Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

✅ async/await and parallelism
C#CC# / help
13mo ago
Learning Streamreader and async / await
C#CC# / help
4mo ago
Async/Await question
C#CC# / help
2w ago
Trying to utilize async and await
C#CC# / help
2y ago