下面的示例假设您已经创建了一个新的包含一个空Worker Role 的Azure PaaS云服务。通过安装Azure .Net SDK将云服务模版添加到Visual Studio。

在部署到云之前,可以在本地使用“Azure服务模拟器”对Worker Role的实现进行测试。 参考MSDN Azure 的文章 "使用模拟器在本地调试和运行一个云服务" 了解更多细节。

Azure PaaS Worker Role的实现和Windows Service 部署场景的例子很相似。
开始使用 Akka.Net 的最快方式是创建一个简单的Worker Role,在它的 RunAsync() 方法里调用 top-level user-actor,如下所示:

WorkerRole.cs

1
using Akka.Actor;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
namespace MyActorWorkerRole
{
public class WorkerRole : RoleEntryPoint
{
private readonly CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
private readonly ManualResetEvent runCompleteEvent = new ManualResetEvent(false);
private ActorSystem _actorSystem;
public override bool OnStart()
{
// Setup the Actor System
_actorSystem = ActorSystem.Create("MySystem");
return (base.OnStart());
}
public override void OnStop()
{
this.cancellationTokenSource.Cancel();
this.runCompleteEvent.WaitOne();
// Shutdown the Actor System
_actorSystem.Shutdown();
base.OnStop();
}
public override void Run()
{
try
{
this.RunAsync(this.cancellationTokenSource.Token).Wait();
}
finally
{
this.runCompleteEvent.Set();
}
}
private async Task RunAsync(CancellationToken cancellationToken)
{
// Create an instance to the top-level user Actor
var workerRoleActor = _actorSystem.ActorOf<WorkerRoleActor>("WorkerRole");
// Send a message to the Actor
workerRoleActor.Tell(new WorkerRoleMessage("Hello World!"));
while (!cancellationToken.IsCancellationRequested)
{
await Task.Delay(1000);
}
}
}
}