Home > Enterprise >  How to do WaitUntil in async?
How to do WaitUntil in async?

Time:09-22

All I can find online talking about await in async is teaching me how to "wait for a certain period of time", which is not what I want.

I want it to wait until a certain condition is met.

Just lile

yield return new WaitUntil(()=>conditionIsMet);

in Coroutine.

I want to do something like

await Task.WaitUntil(()=>conditionIsMet);

Is such thing possible?

Could somebody please be so kind and help me out?

Thank you very much for your help.

CodePudding user response:

Wouldn't this basically simply be something like

public static class TaskUtils
{
    public static Task WaitUntil(Func<bool> predicate)
    {
        while (!predicate()) { }
    }
}

though for the love of your CPU I would actually rather give your task certain sleep intervals like

public static class TaskUtils
{
    public static async Task WaitUntil(Func<bool> predicate, int sleep = 50)
    {
        while (!predicate())
        {
            await Task.Delay(sleep);
        }
    }
}

and now you could e.g. use something like

public class Example : MonoBehaviour
{
    public bool condition;

    private void Start()
    {
        Task.Run(async ()=> await YourTask());
    }

    public async Task YourTask()
    {
        await TaskUtils.WaitUntil(IsConditionTrue);
        // or as lambda
        //await TaskUtils.WaitUntil(() => condition);

        Debug.Log("Hello!");
    }

    private bool IsConditionTrue()
    {
        return condition;
    }
}

enter image description here

CodePudding user response:

you can create your own ConsitionCheker method, and use it in your MainFunction that gets a boolian which awaits for your condition result

 public async Task<bool> CheckCondition()
        {
            While(true){
               // check the condition
               if(mycondition is true)
                  break;
            }
            return true;
        }



 public void Do(bool consitionResult)
    {
        if(consitionResult){
        // codes
        }
    }

usage :

public  async void Test()
        {
            // waiting for condition met
            // pass the condition result
            Do(await CheckCondition());
        }
  • Related