2023-03-06 10:06:43 +04:00
|
|
|
/*
|
|
|
|
|
* Copyright 2023 Eduard Kargin <kargin.eduard@gmail.com>
|
|
|
|
|
*
|
|
|
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
|
|
|
* you may not use this file except in compliance with the License.
|
|
|
|
|
* You may obtain a copy of the License at
|
|
|
|
|
*
|
|
|
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
|
|
|
*
|
|
|
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
|
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
|
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
|
|
|
* See the License for the specific language governing permissions and
|
|
|
|
|
* limitations under the License.
|
|
|
|
|
*/
|
|
|
|
|
|
2022-10-22 21:34:35 +04:00
|
|
|
using System.Threading.Channels;
|
|
|
|
|
|
2023-03-06 10:06:43 +04:00
|
|
|
namespace Ragon.Server;
|
2022-10-22 21:34:35 +04:00
|
|
|
|
2023-03-06 10:06:43 +04:00
|
|
|
public class Executor: TaskScheduler, IExecutor
|
2022-10-22 21:34:35 +04:00
|
|
|
{
|
|
|
|
|
private ChannelReader<Task> _reader;
|
|
|
|
|
private ChannelWriter<Task> _writer;
|
2022-10-22 22:58:15 +04:00
|
|
|
private Queue<Task> _pendingTasks;
|
2022-12-20 12:20:52 -08:00
|
|
|
private TaskFactory _taskFactory;
|
|
|
|
|
|
2022-12-25 03:13:01 -08:00
|
|
|
public void Run(Action action)
|
2022-12-16 00:05:46 +04:00
|
|
|
{
|
2022-12-25 03:13:01 -08:00
|
|
|
_taskFactory.StartNew(action);
|
2022-12-16 00:05:46 +04:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public Executor()
|
2022-10-22 21:34:35 +04:00
|
|
|
{
|
2022-10-22 22:58:15 +04:00
|
|
|
var channel = Channel.CreateUnbounded<Task>();
|
|
|
|
|
_reader = channel.Reader;
|
|
|
|
|
_writer = channel.Writer;
|
2022-12-20 12:20:52 -08:00
|
|
|
|
|
|
|
|
_taskFactory = new TaskFactory(this);
|
2022-12-16 00:05:46 +04:00
|
|
|
_pendingTasks = new Queue<Task>();
|
2022-10-22 21:34:35 +04:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
protected override IEnumerable<Task>? GetScheduledTasks()
|
|
|
|
|
{
|
|
|
|
|
throw new NotSupportedException();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
protected override void QueueTask(Task task)
|
|
|
|
|
{
|
|
|
|
|
_writer.TryWrite(task);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued)
|
|
|
|
|
{
|
|
|
|
|
return false;
|
|
|
|
|
}
|
|
|
|
|
|
2023-03-06 10:06:43 +04:00
|
|
|
public void Update()
|
2022-10-22 21:34:35 +04:00
|
|
|
{
|
|
|
|
|
while (_reader.TryRead(out var task))
|
|
|
|
|
{
|
|
|
|
|
TryExecuteTask(task);
|
|
|
|
|
|
2022-10-23 18:45:37 +04:00
|
|
|
if (task.Status == TaskStatus.Running)
|
2022-10-22 22:58:15 +04:00
|
|
|
_pendingTasks.Enqueue(task);
|
2022-10-22 21:34:35 +04:00
|
|
|
}
|
2022-10-22 22:58:15 +04:00
|
|
|
|
|
|
|
|
while (_pendingTasks.TryDequeue(out var task))
|
|
|
|
|
_writer.TryWrite(task);
|
2022-10-22 21:34:35 +04:00
|
|
|
}
|
|
|
|
|
}
|