《通过C#学Proto.Actor模型》之Spawning
程序员文章站
2022-05-14 18:24:19
Props是配置Actor和实例化Actor,那实例化后,就应该访问了,Props.Actor提供了Actor.Spawn(),Actor.SpawnPrefix(),Actor.SpawnNamed()三个方法,来获取Actor实例,需要注意的是,这些方法返回的并不是真正的Actor对象,而是一个... ......
props是配置actor和实例化actor,那实例化后,就应该访问了,props.actor提供了actor.spawn(),actor.spawnprefix(),actor.spawnnamed()三个方法,来获取actor实例,需要注意的是,这些方法返回的并不是真正的actor对象,而是一个progressid,一个代表actor对象的进程id,缩写pid。
上代码:
1 using proto; 2 using system; 3 using system.threading; 4 using system.threading.tasks; 5 6 namespace p003_spawningactors 7 { 8 class program 9 { 10 static void main(string[] args) 11 { 12 var props = actor.fromproducer(() => new myactor()); 13 14 //产生一个自定义名称的pid 15 var pid1 = actor.spawn(props); 16 pid1.tell(new myentity { id = 1 }); 17 thread.sleep(1000); 18 console.writeline("------------------------------------------"); 19 //产生一个有gsw前缀,跟自动生成的名称的pid 20 var pid2 = actor.spawnprefix(props, "gsw"); 21 pid2.tell(new myentity { id = 2 }); 22 thread.sleep(1000); 23 console.writeline("------------------------------------------"); 24 //产生一个名称为gswpid的pid 25 var pid3 = actor.spawnnamed(props, "gswpid"); 26 pid3.tell(new myentity { id = 3 }); 27 console.readline(); 28 } 29 } 30 31 public class myactor : iactor 32 { 33 public task receiveasync(icontext context) 34 { 35 if (context.message is myentity myentity) 36 { 37 console.writeline($"父 selfid={context.self.id} myentity.id={myentity.id}"); 38 39 var cldprops = actor.fromproducer(() => new mychildactor()); 40 //第一个子actor 41 var pidcld1 = context.spawn(cldprops); 42 pidcld1.tell(new mychildentity { message = "1 message,myentity.id=" + myentity.id }); 43 //第二个子actor 44 var pidcld2 = context.spawnprefix(cldprops, "gswcld"); 45 pidcld2.tell(new mychildentity { message = "2 message,myentity.id=" + myentity.id }); 46 //第三个子actor 47 var pidcld3 = context.spawnnamed(cldprops, "gswcldpid"); 48 pidcld3.tell(new mychildentity { id = 3, message = "3 message,myentity.id=" + myentity.id }); 49 } 50 return actor.done; 51 } 52 } 53 public class mychildactor : iactor 54 { 55 public task receiveasync(icontext context) 56 { 57 if (context.message is mychildentity mychildentity) 58 { 59 console.writeline($"子 selfid={context.self.id} message={mychildentity.message}"); 60 } 61 return actor.done; 62 } 63 } 64 public class myentity 65 { 66 public int id { get; set; } 67 } 68 public class mychildentity 69 { 70 public string message { get; set; } 71 public int id { get; set; } 72 } 73 }
这个例子很简单,说明了三个spawn的使用方式和self.id的特征,包括产生子actor后,子actor的self.id会带有父id,结果如下:
上一篇: 竟然点到了正宗的兰州拉面
下一篇: 婚礼上老公突然成佛了,这婚不用结了吧!
推荐阅读