-
Notifications
You must be signed in to change notification settings - Fork 1k
/
ActorTaskScheduler.cs
212 lines (182 loc) · 7.11 KB
/
ActorTaskScheduler.cs
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
//-----------------------------------------------------------------------
// <copyright file="ActorTaskScheduler.cs" company="Akka.NET Project">
// Copyright (C) 2009-2022 Lightbend Inc. <http://www.lightbend.com>
// Copyright (C) 2013-2022 .NET Foundation <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Akka.Actor;
using Akka.Dispatch.SysMsg;
using Akka.Util.Internal;
namespace Akka.Dispatch
{
/// <summary>
/// TBD
/// </summary>
public class ActorTaskScheduler : TaskScheduler
{
private readonly ActorCell _actorCell;
/// <summary>
/// TBD
/// </summary>
public object CurrentMessage { get; private set; }
/// <summary>
/// Called when async task is scheduled, before Task.StartNew call
/// </summary>
protected virtual void OnBeforeTaskStarted() { }
/// <summary>
/// Called in completed scheduled task continuation
/// </summary>
protected virtual void OnAfterTaskCompleted() { }
/// <summary>
/// TBD
/// </summary>
/// <param name="actorCell">TBD</param>
internal ActorTaskScheduler(ActorCell actorCell)
{
_actorCell = actorCell;
}
/// <summary>
/// TBD
/// </summary>
public override int MaximumConcurrencyLevel
{
get { return 1; }
}
/// <summary>
/// TBD
/// </summary>
/// <returns>TBD</returns>
protected override IEnumerable<Task> GetScheduledTasks()
{
return null;
}
/// <summary>
/// TBD
/// </summary>
/// <param name="task">TBD</param>
protected override void QueueTask(Task task)
{
if ((task.CreationOptions & TaskCreationOptions.LongRunning) == TaskCreationOptions.LongRunning)
{
// Executing a LongRunning task in an ActorTaskScheduler is bad practice, it will potentially
// hang the actor and starve the ThreadPool
// The best thing we can do here is force a rescheduling to at least not execute the task inline.
ScheduleTask(task);
return;
}
// Schedule the task execution, run inline if we are already in the actor context.
if (ActorCell.Current == _actorCell)
{
TryExecuteTask(task);
}
else
{
ScheduleTask(task);
}
}
private void ScheduleTask(Task task)
{
//we are in a max concurrency level 1 scheduler. reading CurrentMessage should be OK
_actorCell.SendSystemMessage(new ActorTaskSchedulerMessage(this, task, CurrentMessage));
}
/// <summary>
/// TBD
/// </summary>
/// <param name="task">TBD</param>
internal void ExecuteTask(Task task)
{
TryExecuteTask(task);
}
/// <summary>
/// TBD
/// </summary>
/// <param name="task">TBD</param>
/// <param name="taskWasPreviouslyQueued">TBD</param>
/// <returns>TBD</returns>
protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued)
{
// Prevent inline execution, it will execute inline anyway in QueueTask if we
// are already in the actor context.
return false;
}
/// <summary>
/// TBD
/// </summary>
/// <param name="action">TBD</param>
public static void RunTask(Action action)
{
RunTask(() =>
{
action();
return Task.CompletedTask;
});
}
/// <summary>
/// TBD
/// </summary>
/// <param name="asyncAction">TBD</param>
/// <exception cref="InvalidOperationException">
/// This exception is thrown if this method is called outside an actor context.
/// </exception>
public static void RunTask(Func<Task> asyncAction)
{
var context = ActorCell.Current;
if (context == null)
throw new InvalidOperationException("RunTask must be called from an actor context.");
var dispatcher = context.Dispatcher;
//suspend the mailbox
dispatcher.Suspend(context);
var actorScheduler = context.TaskScheduler;
actorScheduler.CurrentMessage = context.CurrentMessage;
actorScheduler.OnBeforeTaskStarted();
Task<Task>.Factory.StartNew(asyncAction, CancellationToken.None, TaskCreationOptions.None, actorScheduler)
.Unwrap()
.ContinueWith(parent =>
{
var exception = GetTaskException(parent);
if (exception == null)
{
dispatcher.Resume(context);
context.CheckReceiveTimeout();
}
else
{
context.Self.AsInstanceOf<IInternalActorRef>().SendSystemMessage(new ActorTaskSchedulerMessage(exception, actorScheduler.CurrentMessage));
}
// Used by TestActorRef to intercept async execution result
if(actorScheduler is IAsyncResultInterceptor interceptor)
interceptor.OnTaskCompleted(actorScheduler.CurrentMessage, exception);
//clear the current message field of the scheduler
actorScheduler.CurrentMessage = null;
actorScheduler.OnAfterTaskCompleted();
}, actorScheduler);
}
private static Exception GetTaskException(Task task)
{
switch (task.Status)
{
case TaskStatus.Canceled:
return new TaskCanceledException();
case TaskStatus.Faulted:
return TryUnwrapAggregateException(task.Exception);
}
return null;
}
private static Exception TryUnwrapAggregateException(AggregateException aggregateException)
{
if (aggregateException == null)
return null;
if (aggregateException.InnerExceptions.Count == 1)
return aggregateException.InnerExceptions[0];
return aggregateException;
}
}
}
internal interface IAsyncResultInterceptor
{
void OnTaskCompleted(object message, Exception exception);
}