Skip to content

Instantly share code, notes, and snippets.

@to11mtm
Last active November 24, 2024 04:35
Show Gist options
  • Save to11mtm/9812aea3534ee67493b1a0b44245b051 to your computer and use it in GitHub Desktop.
Save to11mtm/9812aea3534ee67493b1a0b44245b051 to your computer and use it in GitHub Desktop.
Just some crazy POC for dispatchers
/*
MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
// Portions inspired by
// https://github.com/i3arnon/AsyncUtilities/tree/c185cc4a1a859049112b18065c0c772593c786e7/src/AsyncUtilities/TaskEnumerableAwaiter
using System.Runtime.CompilerServices;
using System.Threading.Channels;
using System.Threading.Tasks.Sources;
namespace JFA.Dispatchers;
public abstract class DispatcherItem : ICriticalNotifyCompletion
{
public abstract bool IsCompleted { get; }
public abstract ValueTask Run();
public static ReturnFuncBasedDispatcher<T> Create<T>(Func<Task<T>> action)
{
return new ReturnFuncBasedDispatcher<T>(action);
}
public static NoReturnFuncBasedDispatcherBase Create(Func<Task> action)
{
return new NoReturnFuncBasedDispatcher(action);
}
public static NoReturnFuncBasedDispatcherBase Create<TState>(TState state, Func<TState, Task> action)
{
return new StateHoldingNoReturnFuncBasedDispatcher<TState>(state, action);
}
public abstract void OnCompleted(Action continuation);
public abstract void UnsafeOnCompleted(Action continuation);
public abstract void TrySetError(Exception exception);
public static ReturnFuncBasedDispatcherBase<TResult> Create<TResult, TState>(TState action,
Func<TState, Task<TResult>> func)
{
return new StateHoldingReturnFuncBasedDispatcher<TState, TResult>(action, func);
}
}
public readonly struct ConfiguredTaskNoReturnAwaitable<TResult>
{
internal readonly NoReturnFuncBasedDispatcherBase _item;
/// <summary>Initializes the awaitable.</summary>
/// <param name="tasks">The tasks to be awaited.</param>
/// <param name="continueOnCapturedContext">
/// true to attempt to marshal the continuation back to the original synchronization context captured; otherwise, false.
/// </param>
internal ConfiguredTaskNoReturnAwaitable(NoReturnFuncBasedDispatcherBase item)
{
_item = item;
}
/// <summary>Returns an awaiter for this <see cref="ConfiguredTaskNoReturnAwaitable{TResult}"/> instance.</summary>
public NoReturnFuncBasedDispatcherBase GetAwaiter() =>
_item;
}
public readonly struct ConfiguredTaskReturnAwaitable<TResult>
{
internal readonly ReturnFuncBasedDispatcherBase<TResult> _item;
/// <summary>Initializes the awaitable.</summary>
/// <param name="tasks">The tasks to be awaited.</param>
/// <param name="continueOnCapturedContext">
/// true to attempt to marshal the continuation back to the original synchronization context captured; otherwise, false.
/// </param>
internal ConfiguredTaskReturnAwaitable(ReturnFuncBasedDispatcherBase<TResult> item)
{
_item = item;
}
/// <summary>Returns an awaiter for this <see cref="ConfiguredTaskNoReturnAwaitable{TResult}"/> instance.</summary>
public ReturnFuncBasedDispatcherBase<TResult> GetAwaiter() =>
_item;
}
public abstract class NoReturnFuncBasedDispatcherBase : DispatcherItem, ICriticalNotifyCompletion
{
protected ManualResetValueTaskSourceCore<int> _mrvtcs;
public override bool IsCompleted => _mrvtcs.GetStatus(_mrvtcs.Version) != ValueTaskSourceStatus.Pending;
public NoReturnFuncBasedDispatcherBase(bool noAsync = false)
{
_mrvtcs = new ManualResetValueTaskSourceCore<int>();
_mrvtcs.RunContinuationsAsynchronously = !noAsync;
}
public override void OnCompleted(Action continuation)
{
_mrvtcs.OnCompleted(static o => ((Action)o!)(), continuation, _mrvtcs.Version,
ValueTaskSourceOnCompletedFlags.None);
}
public override void UnsafeOnCompleted(Action continuation)
{
_mrvtcs.OnCompleted(static o => ((Action)o!)(), continuation, _mrvtcs.Version,
ValueTaskSourceOnCompletedFlags.None);
}
public override void TrySetError(Exception exception)
{
_mrvtcs.SetException(exception);
}
public void SetCanceled(Exception ex = null)
{
_mrvtcs.SetException(new TaskCanceledException("The dispatcher was closed", ex));
}
public object GetResult()
{
return default;
}
}
public class NoReturnFuncBasedDispatcher : NoReturnFuncBasedDispatcherBase, ICriticalNotifyCompletion
{
private readonly Func<Task> _toRun;
public override bool IsCompleted => _mrvtcs.GetStatus(_mrvtcs.Version) != ValueTaskSourceStatus.Pending;
public NoReturnFuncBasedDispatcher(Func<Task> toRun, bool noAsync = false)
{
_toRun = toRun;
_mrvtcs = new ManualResetValueTaskSourceCore<int>();
_mrvtcs.RunContinuationsAsynchronously = true;
}
public sealed override async ValueTask Run()
{
try
{
await _toRun();
_mrvtcs.SetResult(0);
}
catch (Exception e)
{
_mrvtcs.SetException(e);
}
}
}
public class StateHoldingNoReturnFuncBasedDispatcher<TState> : NoReturnFuncBasedDispatcherBase,
ICriticalNotifyCompletion
{
private readonly Func<TState, Task> _toRun;
private readonly TState _state;
public override bool IsCompleted => _mrvtcs.GetStatus(_mrvtcs.Version) != ValueTaskSourceStatus.Pending;
public StateHoldingNoReturnFuncBasedDispatcher(TState state, Func<TState, Task> toRun, bool noAsync = false)
{
_state = state;
_toRun = toRun;
_mrvtcs = new ManualResetValueTaskSourceCore<int>();
_mrvtcs.RunContinuationsAsynchronously = true;
}
public sealed override async ValueTask Run()
{
try
{
await _toRun(_state);
_mrvtcs.SetResult(0);
}
catch (Exception e)
{
_mrvtcs.SetException(e);
}
}
}
public abstract class ReturnFuncBasedDispatcherBase<TResult> : DispatcherItem, ICriticalNotifyCompletion
{
protected ManualResetValueTaskSourceCore<TResult> _mrvtcs;
protected ReturnFuncBasedDispatcherBase(bool noAsync)
{
_mrvtcs = new ManualResetValueTaskSourceCore<TResult>();
_mrvtcs.RunContinuationsAsynchronously = !noAsync;
}
public override void OnCompleted(Action continuation)
{
_mrvtcs.OnCompleted(static o => ((Action)o!)(), continuation, _mrvtcs.Version,
ValueTaskSourceOnCompletedFlags.None);
}
public override void UnsafeOnCompleted(Action continuation)
{
_mrvtcs.OnCompleted(static o => ((Action)o!)(), continuation, _mrvtcs.Version,
ValueTaskSourceOnCompletedFlags.None);
}
public override void TrySetError(Exception exception)
{
_mrvtcs.SetException(exception);
}
public TResult GetResult()
{
return (TResult)(object)_mrvtcs.GetResult(_mrvtcs.Version)!;
}
public void SetCanceled(Exception ex = null)
{
_mrvtcs.SetException(new TaskCanceledException("The dispatcher was closed", ex));
}
}
public class ReturnFuncBasedDispatcher<TResult> : ReturnFuncBasedDispatcherBase<TResult>, ICriticalNotifyCompletion
{
private readonly Func<Task<TResult>> _toRun;
public override bool IsCompleted => _mrvtcs.GetStatus(_mrvtcs.Version) != ValueTaskSourceStatus.Pending;
public ReturnFuncBasedDispatcher(Func<Task<TResult>> toRun, bool noAsync = false) : base(noAsync)
{
_toRun = toRun;
_mrvtcs = new ManualResetValueTaskSourceCore<TResult>();
}
public sealed override async ValueTask Run()
{
try
{
_mrvtcs.SetResult(await _toRun());
}
catch (Exception e)
{
_mrvtcs.SetException(e);
}
}
}
public class StateHoldingReturnFuncBasedDispatcher<TState, TResult> : ReturnFuncBasedDispatcherBase<TResult>,
ICriticalNotifyCompletion
{
private readonly Func<TState, Task<TResult>> _toRun;
private readonly TState _state;
public override bool IsCompleted => _mrvtcs.GetStatus(_mrvtcs.Version) != ValueTaskSourceStatus.Pending;
public StateHoldingReturnFuncBasedDispatcher(TState state, Func<TState, Task<TResult>> toRun,
bool noAsync = false) : base(noAsync)
{
_state = state;
_toRun = toRun;
}
public sealed override async ValueTask Run()
{
try
{
_mrvtcs.SetResult(await _toRun(_state));
}
catch (Exception e)
{
_mrvtcs.SetException(e);
}
}
public override void TrySetError(Exception exception)
{
_mrvtcs.SetException(exception);
}
}
public class AsyncChannelDispatcher
{
public readonly Channel<DispatcherItem> _ch = Channel.CreateUnbounded<DispatcherItem>();
private readonly Task _taskSet;
public AsyncChannelDispatcher(int maxThreads, bool configureAwaitFalse = false)
{
var caw = !configureAwaitFalse;
var taskArr = new Task[maxThreads];
for (int i = 0; i < maxThreads; i++)
{
taskArr[i] = Task.Run(async () =>
{
try
{
while (await _ch.Reader.WaitToReadAsync())
{
while (_ch.Reader.TryRead(out var item))
{
try
{
await item.Run().ConfigureAwait(caw);
}
catch (Exception e)
{
item.TrySetError(e);
}
}
}
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
return 0;
});
}
_taskSet = Task.WhenAll(taskArr);
}
public async Task ScheduleAction(Func<Task> action)
{
var item = DispatcherItem.Create(action);
if (!_ch.Writer.TryWrite(item))
{
item.SetCanceled();
}
await new ConfiguredTaskNoReturnAwaitable<object>(item);
}
public async Task ScheduleAction<TState>(TState state, Func<TState, Task> action)
{
var item = DispatcherItem.Create<TState>(state, action);
if (!_ch.Writer.TryWrite(item))
{
item.SetCanceled();
}
await new ConfiguredTaskNoReturnAwaitable<object>(item);
}
public async Task<TResult> ScheduleAction<TResult>(Func<Task<TResult>> action)
{
var item = DispatcherItem.Create(action);
if (!_ch.Writer.TryWrite(item))
{
item.SetCanceled();
}
return await new ConfiguredTaskReturnAwaitable<TResult>(item);
}
public async Task<TResult> ScheduleAction<TState, TResult>(TState state, Func<TState, Task<TResult>> action)
{
var item = DispatcherItem.Create(state, action);
if (!_ch.Writer.TryWrite(item))
{
item.SetCanceled();
}
return await new ConfiguredTaskReturnAwaitable<TResult>(item);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment