-
Notifications
You must be signed in to change notification settings - Fork 64
/
Copy pathChannelTickScheduler.cs
122 lines (100 loc) · 3.39 KB
/
ChannelTickScheduler.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
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Channels;
using System.Threading.Tasks;
namespace AltV.Net.Async
{
internal class ChannelTickScheduler : TaskScheduler , ITickScheduler
{
private readonly Thread mainThread;
public override int MaximumConcurrencyLevel { get; } = 1;
private readonly Channel<Task> tasks = Channel.CreateUnbounded<Task>(new UnboundedChannelOptions
{SingleReader = true});
private Task currentTask;
private readonly ChannelReader<Task> reader;
private readonly ChannelWriter<Task> writer;
private readonly TaskFactory taskFactory;
public ChannelTickScheduler(Thread mainThread)
{
this.mainThread = mainThread;
reader = tasks.Reader;
writer = tasks.Writer;
taskFactory = new TaskFactory(
CancellationToken.None, TaskCreationOptions.DenyChildAttach,
TaskContinuationOptions.None, this);
}
protected override IEnumerable<Task> GetScheduledTasks() => null;
protected override void QueueTask(Task task) => writer.WriteAsync(task);
protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued) =>
Thread.CurrentThread == mainThread && TryExecuteTask(task);
public void Schedule(Action action)
{
taskFactory.StartNew(action);
}
public void ScheduleBlocking(Action action, SemaphoreSlim semaphoreSlim)
{
taskFactory.StartNew(() =>
{
try
{
action();
}
catch (Exception exception)
{
Console.WriteLine(exception);
}
semaphoreSlim.Release();
});
semaphoreSlim.Wait();
}
public void ScheduleBlockingThrows(Action action, SemaphoreSlim semaphoreSlim)
{
Exception exception = null;
taskFactory.StartNew(() =>
{
try
{
action();
}
catch (Exception innerException)
{
exception = innerException;
}
semaphoreSlim.Release();
});
semaphoreSlim.Wait();
if (exception != null)
{
throw exception;
}
}
public void Schedule(Action<object> action, object state)
{
taskFactory.StartNew(action, state);
}
public Task ScheduleTask(Action action)
{
return taskFactory.StartNew(action);
}
public Task ScheduleTask(Action<object> action, object state)
{
return taskFactory.StartNew(action, state);
}
public Task<TResult> ScheduleTask<TResult>(Func<TResult> action)
{
return taskFactory.StartNew(action);
}
public Task<TResult> ScheduleTask<TResult>(Func<object, TResult> action, object value)
{
return taskFactory.StartNew(action, value);
}
public void Tick()
{
while (reader.TryRead(out currentTask))
{
TryExecuteTask(currentTask);
}
}
}
}