我创建了singleton
包装器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;
}
}
}
当我从同步代码中使用它时,一切都很好!但是当Actor
's 是并行创建Task
的
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();
}
项目在包装器的 ctor 之后停止
this.director = ActorSystem.Create("ActorDirector", config);
并且不能进一步工作。
有趣的是,如果在循环中我们限制不超过 20 个,但不超过 8 个,那么随着一些延迟,一切都会起作用。
有人可以告诉我我做错了什么以及如何解决它。