I have the following extension method for monitoring a variable and awaiting until it has a given expected value:
public static async Task AwaitForValue<T>(this Func<T> valueGetter, T expectedValue, int? millisecondsToAwaitBetweenChecks = null, int? maxMillisecondsToAwait = null)
where T : struct
{
var timeToAwait = millisecondsToAwaitBetweenChecks ?? 20;
if (maxMillisecondsToAwait.HasValue)
{
var stopWatch = new Stopwatch();
stopWatch.Start();
while (!valueGetter().Equals(expectedValue) || stopWatch.ElapsedMilliseconds >= maxMillisecondsToAwait)
{
await Task.Delay(timeToAwait);
}
}
else
{
while (!valueGetter().Equals(expectedValue))
{
await Task.Delay(timeToAwait);
}
}
}
It is working just fine:
class Foo
{
private bool _flag;
public async void DoWork()
{
Task.Run(() =>
{
Thread.Sleep(5000);
_flag = true;
});
await new Func<bool>(() => _flag).AwaitForValue(true);
Console.WriteLine(_flag);
}
}
I would like to define a ref extension method that gives me a delegate that returns me the current value of the ref variable, something like:
public delegate ref T RefFunc<T>();
This way my previous extension method could extend RefFunc<T>
instead of Func<T>
and be consumed, hypothetically, like the following:
_flag.ToRefFunc().AwaitForValue(true);
The problem is that I can not find a way to properly define ToRefFunc<T>(this ref T value);
since ref
is not allowed in lambdas. So, is there a way to define the following method?
public static RefFunc<T> ToRefFunc<T>(this ref T value) where T : struct
{
//todo some day
}
Ideally it will look like this:
public static RefFunc<T> ToRefFunc<T>(this ref T value) where T : struct => new RefFunc<T>(() => value);
Any help would be appreciated
EDIT
The problem is not whether ref extension methods are allowed, from the "duplicate" question see this
EDIT 2 The anonymous delegate syntax does not work either:
public static RefFunc<T> ToRefFunc<T>(this ref T value) where T: struct
{
return delegate { return value; };
}
Here I got: Cannot use ref, out, or in parameter 'value' inside an anonymous method, lambda expression, query expression, or local function