Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create Wait task that loops until true or timeout

Tags:

c#

async-await

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;
    }
like image 855
Kyle Avatar asked Sep 27 '22 17:09

Kyle


1 Answers

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());     
like image 189
NeddySpaghetti Avatar answered Oct 03 '22 13:10

NeddySpaghetti