Code · 105 lines · 2403 bytes
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
105using System;
using System.Threading;
using System.Threading.Tasks;

namespace Xtremegaida.DataStructures;

[System.Diagnostics.DebuggerDisplay("TriggerState = {triggerState}")]
public struct EventWaitLight
{
	private SpinLock taskLock;
	private TaskCompletionSource taskSource;
	private Exception lastError;
	private volatile int triggerState;

	public bool Triggered => triggerState != 0;

	public Task WaitAsync(CancellationToken cancellationToken = default)
	{
		if (cancellationToken.IsCancellationRequested) { return Task.FromCanceled(cancellationToken); }
		Task task;
		bool locked = false;
		try
		{
			taskLock.TryEnter(ref locked);
			if (triggerState != 0)
			{
				var error = lastError;
				if (triggerState > 0) { triggerState = 0; lastError = null; }
				if (error != null) { return Task.FromException(error); }
				return Task.CompletedTask;
			}
			if (taskSource == null) { taskSource = new TaskCompletionSource(); }
			task = taskSource.Task;
		}
		finally
		{
			if (locked) { taskLock.Exit(); }
		}
		if (cancellationToken.CanBeCanceled) { return task.WaitAsync(cancellationToken); }
		return task;
	}

	public void Trigger(Exception error = null, bool manualReset = false, bool withReEntrantSafety = false)
	{
		// WARNING: TrySetResult runs continuations synchronously on the same thread.
		// This can cause issues with non-reentrant locking.
		TaskCompletionSource source = null;
		bool locked = false;
		try
		{
			taskLock.Enter(ref locked);
			lastError = error; triggerState = 1;
			if (taskSource != null)
			{
				source = taskSource; taskSource = null;
				lastError = null; triggerState = 0;
			}
			if (manualReset) { triggerState = -1; }
		}
		finally
		{
			if (locked) { taskLock.Exit(); }
		}
		if (source != null)
		{
			if (withReEntrantSafety)
			{
				RunAsTask(source, error);
			}
			else
			{
				if (error != null) { source.TrySetException(error); }
				else { source.TrySetResult(); }
			}
		}
	}

	private void RunAsTask(TaskCompletionSource source, Exception error)
	{
		_ = Task.Run(() =>
		{
			if (error != null) { source.TrySetException(error); }
			else { source.TrySetResult(); }
		});
	}

	public void Reset()
	{
		bool locked = false;
		try
		{
			taskLock.Enter(ref locked);
			if (triggerState != 0)
			{
				taskSource = null;
				lastError = null;
				triggerState = 0;
			}
		}
		finally
		{
			if (locked) { taskLock.Exit(); }
		}
	}
}