I am trying to use the below function to not return a true/false unless the Boolean Function arg returns true or the timeout expires. In its current state if the Boolean Function arg returns false it immediately returns false instead of looping and retrying for X more milliseconds.
public delegate bool BooleanFunction ();
public static async Task<bool> Wait(uint Milliseconds, BooleanFunction Function)
{
var StartTime = Environment.TickCount;
do
{
if (Function())
{
return true;
}
Thread.Yield();
}
while (Environment.TickCount < StartTime + Milliseconds);
return false;
}
You need to use await Task.Yield
instead of Thread.Yield
if (Function())
{
return true;
}
await Task.Yield();
If you also want to handle passing asynchronous delegates to Wait
, keep the existing version and add the following overload:
public static async Task<bool> Wait(uint Milliseconds, Func<Task<bool>> Function)
{
var StartTime = Environment.TickCount;
do
{
if (await Function())
{
return true;
}
Thread.Yield();
}
while (Environment.TickCount < StartTime + Milliseconds);
return false;
}
Then you can do this:
var result = await Wait(10000, async () => await Test());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With