C# Akka multithreaded creating of actors

274 views Asked by At

I created singleton wrapper over ActorSystem

using System;
using System.IO;
using System.Linq;
using System.Threading;
using System.Xml.Linq;

using Akka.Actor;
using Akka.Configuration;

namespace AkkaPOC
{
    public sealed class ActorsDirector : IDisposable
    {    
        private static readonly Lazy<ActorsDirector> instance =
            new Lazy<ActorsDirector>(() =>
                new ActorsDirector(),
                LazyThreadSafetyMode.ExecutionAndPublication);

        public static ActorSystem Instance
            => instance.Value.director;

        private readonly ActorSystem director;

        private ActorsDirector()
        {
            var config  = ConfigurationFactory.ParseString(
                XElement.Parse(File.ReadAllText(@$"{Directory.GetCurrentDirectory()}\akka.config"))
                        .Descendants("hocon")
                        .Single()
                        .Value);

            this.director = ActorSystem.Create("ActorDirector", config);
        }

        bool isDisposed = false;

        ~ActorsDirector()
        {
            Dispose(false);
        }

        /// <inheritdoc/>
        public void Dispose()
        {
            this.Dispose(true);
            GC.SuppressFinalize(this);
        }

        private void Dispose(bool disposing)
        {
            if (this.isDisposed)
                return;
            if (disposing)
            {
                this.director.Dispose();
            }

            this.isDisposed = true;
        }
    }
}

And when I use it from synchronously code all is fine! But when Actor's are created in parallel Task's

for (int i = 0; i < 20; i++)
{
    new Task(() =>
    {
        var actor = ActorsDirector.Instance
                                    .ActorOf<AskerActor>()
                                    .Ask<T>(parameters)
        actor.Wait();
        Console.WriteLine("uint: {0}", actor.Result);
    }).Start();
}

project stops in wrapper's ctor after

this.director = ActorSystem.Create("ActorDirector", config);

and doesn`t work further.

Which is interesting, if in the cycle we make a restriction not of 20, but not more than 8, then with some delay everything will work.

Can someone say me what I do incorrect and how to fix it.

0

There are 0 answers