using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Runtime.ExceptionServices;
using System.Threading.Tasks;
using STT=System.Threading.Tasks;
using CMN=System.Runtime.CompilerServices.CallerMemberNameAttribute;
using CFP=System.Runtime.CompilerServices.CallerFilePathAttribute;
using CLN=System.Runtime.CompilerServices.CallerLineNumberAttribute;
using DN=System.Diagnostics.CodeAnalysis.DisallowNullAttribute;
using dt=System.DateTime;
public readonly record struct ReadOnlyForAllThreads<T>
public ReadOnlyForAllThreads(T value) => theValue=theValue.Equals(default(T)) ? value : theValue;
private static T theValue {get;set;}
public static implicit operator T(ReadOnlyForAllThreads<T> fat)=>theValue;
public static explicit operator ReadOnlyForAllThreads<T>(T value)=>new ReadOnlyForAllThreads<T>(value);
public async static Task Main()
var fat=new ReadOnlyForAllThreads<int>(5);
var fat2=new ReadOnlyForAllThreads<int>(6);
Console.WriteLine("Bugs in main method\n");
var t=p.GetString("Hello ");
Console.WriteLine($"is T null...{t is null}");
Console.WriteLine($"t.Result: {t.Result}");
Console.WriteLine(">awaited t=" + await t);
Console.WriteLine("\nafter call\n");
foreach(var k in ManagedTaskBroker.Logs)
Console.WriteLine($"KEY: {k.Key.ToString()} \nVALUE: {k.Value.ToString()}\n");
public async ManagedTask<string> GetString2(str s)
var t = ManagedTask<int>.Run(async delegate
Console.WriteLine(await t);
public async ManagedTask<string> GetString(string s)
var temp=new ManagedTask<string>(async ()=> {await Task.Delay(1000); return "Daffy TOO";} );
Console.WriteLine( await temp );
Console.WriteLine( temp.Result );
var t=ManagedTask<string>.Run( ()=> { Console.WriteLine("INSIDE");return s + " Bugs"; });
public readonly record struct CallerInformationKey(str Name, int Line, str Path)
public override string ToString() => $"(Name: {Name}, Line: {Line}, Path: {Path})";
public record CalledInformationValue2(int FastTasks, int SlowTasks)
public dt RunDT=dt.UtcNow;
public TimeSpan? Duration;
public int FastTasks, SlowTasks;
public int TotalTasks {get=>FastTasks+SlowTasks;}
public decimal PercentSlow {get=>TotalTasks==0 || SlowTasks==0 ? 0m : Convert.ToDecimal(SlowTasks)/Convert.ToDecimal(TotalTasks) * 100m;}
public override string ToString() => $"(TotalTasks: {TotalTasks}, FastTasks: {FastTasks}, SlowTasks: {SlowTasks}, % Slow: {PercentSlow})";
public class TelemetryCallerSummary
public class CalledInformationSummaryValue
public dt RunDT=dt.UtcNow;
public TimeSpan Duration {get;set;}
public str Name, Path, ReturnType;
public bool IsPrimitiveReturnType;
public dt LastUpdate {get;set;}=dt.UtcNow;
public int FastTasks {get;set;}
public int SlowTasks {get;set;}
public List<CalledInformationEntryValue> Entries=new();
public int TotalTasks {get=>FastTasks+SlowTasks;}
public decimal PercentSlow {get=>TotalTasks==0 || SlowTasks==0 ? 0m : Convert.ToDecimal(SlowTasks)/Convert.ToDecimal(TotalTasks) * 100m;}
public override string ToString() => $"TotalTasks: {TotalTasks}, FastTasks: {FastTasks}, SlowTasks: {SlowTasks}, % Slow: {PercentSlow}\n\tLastUpdate: {LastUpdate} Duration: {Duration.Ticks} ticks";
public readonly record struct CalledInformationEntryValue (dt StartDT, dt EndDT, str ReturnType, bool IsPrimativeReturnType, bool IsSlow)
public TimeSpan Duration {get=>EndDT-StartDT;}
public class Manager : ConcurrentDictionary<CallerInformationKey, CalledInformationSummaryValue>
public DetailMode DetailMode {get;set;}=DetailMode.Verbose;
public void IncrementSlowPath(CallerInformationKey callerKey, TimeSpan duration)
if(String.IsNullOrWhiteSpace(callerKey.Name)) return;
key=>new CalledInformationSummaryValue{FastTasks=0,SlowTasks=1,Duration=duration},
(key, oldValue)=>new CalledInformationSummaryValue{FastTasks=oldValue.FastTasks, SlowTasks=oldValue.SlowTasks+1, LastUpdate=dt.UtcNow, Duration=duration }
public void IncrementFastPath(CallerInformationKey callerKey, TimeSpan duration)
if(String.IsNullOrWhiteSpace(callerKey.Name)) return;
key=>new CalledInformationSummaryValue{FastTasks=1,SlowTasks=0,Duration=duration},
(key, oldValue)=>new CalledInformationSummaryValue{FastTasks=oldValue.FastTasks+1, SlowTasks=oldValue.SlowTasks, LastUpdate=dt.UtcNow, Duration=duration}
public enum DetailMode { Summary, Verbose }
public class ManagedTaskBroker
public static Telemetry.Manager Logs=new();
public record Configuration
List<ConfigurationTrigger> triggers=new();
public record ConfigurationTrigger
int minRunsBeforeEvaluation =10;
decimal thresholdForValueSwitch =.8m;
int telemetryFrequency =1;
IConfigurationTrigger trigger;
public interface IConfigurationTrigger
public Func<bool> CheckConditionToFire(Telemetry.Manager telemetry);
public partial class ManagedTask
public static Task Delay(int milliseconds)
return Task.Delay(milliseconds);
[AsyncMethodBuilder(typeof(ManagedTaskBuilder<>))]
public partial class ManagedTask<T> : IAwaitable<T>
public bool configureAwait {get;set;}=false;
public TaskContinuationOptions continuationOptions {get;set;}=TaskContinuationOptions.DenyChildAttach | TaskContinuationOptions.ExecuteSynchronously;
public TaskCreationOptions creationOptions {get;set;}=TaskCreationOptions.DenyChildAttach;
internal CallerInformationKey callerKey;
private Lazy<IAwaiter<T>> _taskAwaiter;
private Lazy<IAwaiter<T>> _valueTaskAwaiter;
private bool _isTaskStarted=false;
private bool _isValueTask {get;set;}=false;
private Func<T>? _function;
private Func<Task<T>>? _functionT;
private ValueTask<T> _valueTask;
private Exception _exception;
private static str FullName;
static ManagedTask() { FullName=typeof(ManagedTask).FullName; Console.WriteLine("FullName: " + FullName);}
public ManagedTask([DN]Func<T> function, bool configureAwait=false, [CMN]str callerName="", [CLN] int callerLineNumber=0, [CFP] str callerFilePath="")
( callerKey, this.configureAwait, _function, _task)=
( new (Name:callerName,Line:callerLineNumber,Path:callerFilePath), configureAwait, function, Task<T>.Run(function) );
Console.WriteLine($"ManagedTask<T>.ctor (function: {function is null}, {_task.Status})");
public ManagedTask([DN]Func<Task<T>> functionT, bool configureAwait=false, [CMN]str callerName="", [CLN] int callerLineNumber=0, [CFP] str callerFilePath="")
( callerKey, this.configureAwait, _functionT, _task) =
( new (Name:callerName,Line:callerLineNumber,Path:callerFilePath), configureAwait, functionT, functionT() );
Console.WriteLine($"ManagedTask<T>.ctor (Func<task>: {functionT is null}), {_task is null}, {_task.Status}");
public ManagedTask([DN]Task<T> task, bool configureAwait=false, bool autoStartTask=false, [CMN]str callerName="", [CLN] int callerLineNumber=0, [CFP] str callerFilePath="")
( callerKey, this.configureAwait, _task ) =
( new (Name:callerName,Line:callerLineNumber,Path:callerFilePath), configureAwait, task );
Console.WriteLine($"ManagedTask<T>.ctor (task: {task is null})");
if(autoStartTask) _task.Start();
internal ManagedTask([DN]T fromResult, [CMN]str callerName="", [CLN] int callerLineNumber=0, [CFP] str callerFilePath="")
( callerKey, _isValueTask, _valueTask ) =
( new (Name:callerName,Line:callerLineNumber,Path:callerFilePath), true, new ValueTask<T>(fromResult) );
Console.WriteLine($"ManagedTask<T>.ctor (fromResult: {fromResult is null})");
internal ManagedTask(Exception fromException, [CMN]str callerName="", [CLN] int callerLineNumber=0, [CFP] str callerFilePath="")
( callerKey, _isValueTask, _valueTask, _exception ) =
( new (Name:callerName,Line:callerLineNumber,Path:callerFilePath), true, ValueTask.FromException<T>(fromException), fromException );
Console.WriteLine("ManagedTask.init start");
_taskAwaiter=new Lazy<IAwaiter<T>>( ()=>new ManagedTaskAwaiter<T>(_task!, callerKey, dt.UtcNow) );
_valueTaskAwaiter=new Lazy<IAwaiter<T>>( ()=>new ManagedTaskAwaiter<T>(_valueTask!, callerKey, dt.UtcNow) );
_task?.ConfigureAwait(configureAwait);
_valueTask.ConfigureAwait(configureAwait);
Console.WriteLine("ManagedTask.init end");
Console.WriteLine($"{_task.Status}");
if(_isTaskStarted) return;
if(_task.Status==TaskStatus.Created) _task.Start();
get=>!_isValueTask ? _task!.IsCompleted : _valueTask.IsCompleted;
if(_isValueTask) _task??=_valueTask.AsTask();
public IAwaiter<T> GetAwaiter()
Console.WriteLine($"ManagedTask<T>.GetAwaiter");
return _isValueTask ? _valueTaskAwaiter.Value : _taskAwaiter.Value;
if (!_isValueTask) TaskAwait();
return _result??=!_isValueTask ? _task!.Result : _valueTask.Result ;
async void TaskAwait() => await _task!.ConfigureAwait(configureAwait);
async void ValueTaskAwait() => await _valueTask.ConfigureAwait(configureAwait);
public ManagedTask<T> ContinueWith(Func<T, Task<T>> func)
=>new ManagedTask<T>(()=>func(Result));
public ManagedTask<OUT> ContinueWith<OUT>(Func<T, Task<OUT>> func)
=>new ManagedTask<OUT>(()=>func(Result));
public partial class ManagedTask<T>
public static IAwaitable<T> FromException([DN]Exception fromException, [CMN]str callerName="", [CLN] int callerLineNumber=0, [CFP] str callerFilePath="")
Console.WriteLine($"ManagedTask<T>.FromException");
var returned=new ManagedTask<T>(fromException:fromException!, callerName:callerName, callerLineNumber:callerLineNumber, callerFilePath:callerFilePath);
public static IAwaitable<T> FromResult([DN]T fromResult, [CMN]str callerName="", [CLN] int callerLineNumber=0, [CFP] str callerFilePath="")
Console.WriteLine($"ManagedTask<T>.FromResult");
var returned=new ManagedTask<T>(fromResult:fromResult!, callerName:callerName, callerLineNumber:callerLineNumber, callerFilePath:callerFilePath);
public static IAwaitable<T> Run(Func<Task<T>> f, bool configureAwait=false, [CMN]str callerName="", [CLN] int callerLineNumber=0, [CFP] str callerFilePath="")
Console.WriteLine("ManagedTask.Run<Task<T>>");
var iA=new ManagedTask<T>(functionT:f, configureAwait:configureAwait, callerName:callerName, callerLineNumber:callerLineNumber, callerFilePath:callerFilePath);
public static IAwaitable<T> Run(Func<T> f, bool configureAwait=false, [CMN]str callerName="", [CLN] int callerLineNumber=0, [CFP] str callerFilePath="")
Console.WriteLine("ManagedTask.Run<T>");
var iA=new ManagedTask<T>(function:f, configureAwait:configureAwait, callerName:callerName, callerLineNumber:callerLineNumber, callerFilePath:callerFilePath);
public static implicit operator ManagedTask<T>(Task<T> task)
Console.WriteLine($"Implicit 1");
public static explicit operator ManagedTask<T>([DN]T result)
Console.WriteLine($"Explicit");
return new ManagedTask<T>(fromResult:result!);
public static implicit operator Task<T>([DN]ManagedTask<T> managedTask)
Console.WriteLine($"Implicit 2");
return managedTask._task!;
public struct ManagedTaskAwaiter<T> : IAwaiter<T>, ICriticalNotifyCompletion
private readonly Task<T>? _task {get;init;}
private readonly ValueTask<T> _valueTask {get;init;}
private bool _gotResult=false;
private bool _isCompleted=false;
private bool _isValueTask=false;
private int lastHashCode;
private CallerInformationKey callerKey;
private TaskAwaiter<T>? awaiter;
public ManagedTaskAwaiter([DN]Task<T>? t, CallerInformationKey callerKey, dt startRunDT) => (this.callerKey, _task, this.startRunDT)=(callerKey, t!, startRunDT);
public ManagedTaskAwaiter([DN]ValueTask<T> t, CallerInformationKey callerKey, dt startRunDT)
=> (this.callerKey, _valueTask, _isValueTask, this.startRunDT) = (callerKey, t, true, startRunDT);
awaiter??=_isValueTask ? _valueTask.GetAwaiter() : _task!.GetAwaiter();
if(!_isCompleted) _isCompleted=_isValueTask ? _valueTask.GetAwaiter().IsCompleted : _task!.GetAwaiter().IsCompleted;
Console.WriteLine($"Awaiter.IsCompleted={_isCompleted} (_valueTask:{_valueTask==null},_task={_task is null}, HashCode={lastHashCode})");
int compareHashCode=_isValueTask ? _valueTask.GetHashCode() : _task!.GetHashCode();
if(compareHashCode!=lastHashCode)
if(!_isCompleted) ManagedTaskBroker.Logs.IncrementSlowPath(callerKey, dt.UtcNow-startRunDT);
else ManagedTaskBroker.Logs.IncrementFastPath(callerKey, dt.UtcNow-startRunDT);
lastHashCode=compareHashCode;
Console.WriteLine($"!!!Awaiter.IsComplete duplicate (Hashcode={lastHashCode})");
Console.WriteLine($"Awaiter.GetResult");
if(!_gotResult) (_gotResult, _result)=( true, _isValueTask ? _valueTask.GetAwaiter().GetResult() :_task!.GetAwaiter().GetResult() );
public void OnCompleted(Action continuation)
Console.WriteLine($"Awaiter.OnCompleted({continuation==null})");
public void UnsafeOnCompleted(Action continuation)
Console.WriteLine($"Awaiter.UnsafeOnCompleted({continuation==null})");
public struct ManagedTaskBuilder<T>
private AsyncTaskMethodBuilder<T> builder=new AsyncTaskMethodBuilder<T>();
private Exception? _exception;
private TaskCompletionSource<T>? tcs;
private bool isSlow=false;
public ManagedTaskBuilder()
Console.WriteLine($"Builder.CTOR");
public static ManagedTaskBuilder<T> Create() => new ManagedTaskBuilder<T>();
public readonly void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine => stateMachine.MoveNext();
public ManagedTask<T> Task
ManagedTask<T> returnedTask=default;
_lock.Enter(ref lockTaken);
if (_exception is not null)
return returnedTask=new ManagedTask<T>(fromException:_exception, callerName:null);
return returnedTask=new ManagedTask<T>(fromResult:_result!, callerName:null);
return returnedTask=new ManagedTask<T>( task:(new TaskCompletionSource<T>(TaskCreationOptions.RunContinuationsAsynchronously).Task) );
public void SetResult(T result)
Console.WriteLine($"Builder.SetResult(Result={result})");
_lock.Enter(ref lockTaken);
Console.WriteLine($"_result:{_result}");
public readonly void SetStateMachine(IAsyncStateMachine stateMachine) {}
public void SetException(Exception exception)
_lock.Enter(ref lockTaken);
public void AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine)
where TAwaiter : INotifyCompletion
where TStateMachine : IAsyncStateMachine
Console.WriteLine("Builder.AwaitOnCompleted");
public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine)
where TAwaiter : ICriticalNotifyCompletion
where TStateMachine : IAsyncStateMachine
Console.WriteLine($"Builder.AwaitUnsafeOnCompleted (awaiter={awaiter==null}, stateMachine={stateMachine==null})");
stateMachine!.MoveNext();
Action a=stateMachine.MoveNext;
public interface IAwaitable
public IAwaiter GetAwaiter();
public interface IAwaitable<T>
public IAwaiter<T> GetAwaiter();
public interface IAwaiter : ICriticalNotifyCompletion
public bool IsCompleted { get; }
public interface IAwaiter<T> : ICriticalNotifyCompletion
public bool IsCompleted { get; }