我不确定这是否与 akka.net 或 TPL 更多相关,但我将使用 actor 作为示例来澄清问题。
简而言之,问题是:有什么方法可以告诉 akka.net 一次触发比我实际拥有的 CPU 核心更多的线程吗?这是示例代码和详细信息:
我目前使用的是带有 8 核处理器的笔记本电脑。假设我要创建 20 个演员:
for (int i = 0; i < 20; i++)
{
actorList.Add(system.ActorOf<ExampleActor>());
}
然后我向所有这些人传递一条信息:
actorList[0].Tell(new ExampleMessage());
Console.WriteLine("sent message to actor 1\t" + DateTime.Now.TimeOfDay);
actorList[1].Tell(new ExampleMessage());
Console.WriteLine("sent message to actor 2\t" + DateTime.Now.TimeOfDay);
...
actorList[19].Tell(new ExampleMessage());
Console.WriteLine("sent message to actor 20\t" + DateTime.Now.TimeOfDay);
演员在接收消息时所做的所有事情都是以下虚假的长期运行过程:
Console.WriteLine("Accessing slow service\t" + DateTime.Now.TimeOfDay
+ "\t" + Thread.CurrentThread.ManagedThreadId);
Thread.Sleep(60000);
Console.WriteLine("Service call was successful\t" + DateTime.Now.TimeOfDay
+ "\t" + Thread.CurrentThread.ManagedThreadId);
我还在其构造函数中包含此代码,以便我知道演员何时实际创建:
public ExampleActor()
{
Console.WriteLine("Creating " + this.Self.Path + DateTime.Now.TimeOfDay);
....
}
因此,现在当我运行应用程序时,我首先会在同一毫秒内收到所有 20 个演员的“已发送消息给演员”行。但之后,当初始化的时候,首先只创建了 8 个 actor。
然后,由于其他演员都没有完成这项工作,正好 1 秒后,另一个演员被初始化(第 9 个演员)。又过了一秒,我们创建了第 10 个 actor,并开始了 Thread.Sleep 操作。
现在的问题是,有没有办法告诉 akka.net(或其下面的 TPL)我确定线程将为每个服务调用等待大约 60 秒?这样所有 20 个线程都会立即启动,而不是立即启动 8 个线程,并且在 12 秒过去后才运行全部 20 个线程?