简体   繁体   English

如何使异步任务返回true或false?

[英]How can I make an async Task return true or false?

I am calling a task like this in my method: 我在我的方法中调用了这样的任务:

if (Settings.mode.IsPractice() && App.practiceRunning != true)
{
   // I want to call this method and check if it returned true or false
   await IsPractice();
}

private async Task IsPractice()
{
    // I want to return true or false from here
}

How can I return from the method based on the value of the IsPractice() returning a true or false? 如何基于IsPractice()的值返回true或false的方法从方法返回? Looks like the async method returns just a Task but I need to know if it ran and returned a true or a false. 看起来async方法仅返回一个Task,但我需要知道它是否已运行并返回true或false。

Use the generic Task type: 使用通用任务类型:

if (Settings.mode.IsPractice() && App.practiceRunning != true)
{
    if (await IsPractice()) {
        // Do something here
    }
}

private async Task<bool> IsPractice()
{
    return true;
}
 private static async Task<bool> IsPractice()
    {
     return true;   
    }

and in async method receive like this 并在异步方法中收到这样

bool x =  await IsPractice();

just add <bool> 只需添加<bool>

private async Task<bool> IsPractice()
{
    return true;
}

or just use async bool 或只使用async bool

private async bool IsPractice()
{
    return true;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM