简体   繁体   English

如何返回依赖于在方法中启动的协同程序的结果的值? (C#)

[英]How do you return a value that is dependent on the result of a co-routine that is started within the method? (C#)

I have a public method that returns a bool.我有一个返回布尔值的公共方法。 The method starts a co-routine.该方法启动一个协同程序。 The co-routine is what determines the value of the bool.协程决定了 bool 的值。 I just realized that the method will return the bool without waiting for the coroutine to finish.我刚刚意识到该方法将在不等待协程完成的情况下返回 bool。 I am at a loss on how to achieve this.我对如何实现这一目标感到茫然。

An example.一个例子。 Let's say a separate class is calling this:假设一个单独的类正在调用它:

public bool CheckListForName(string username)
{
    StartCoroutine(DownloadPlayer(username));
    return playerExists;
}

I realize this code is meaningless without context, but if the bool "playerExists" is set to "False" by default, but the coroutine "DownloadPlayer" would find that "playerExists" should actually be true, it won't matter, because "CheckListForName" will have already returned "false" before the coroutine found the correct value.我意识到这段代码在没有上下文的情况下毫无意义,但是如果默认情况下将 bool "playerExists" 设置为 "False",但协程 "DownloadPlayer" 会发现 "playerExists" 实际上应该为真,这无关紧要,因为 " CheckListForName”将在协程找到正确值之前已经返回“false”。

I am relatively new to programming, so any help is very appreciated!我对编程比较陌生,所以非常感谢任何帮助!

You might want to consider using async/await您可能需要考虑使用 async/await

public async Task<bool> CheckListForName(string username)
{
    await DownloadPlayer(username);
    return playerExists;
}

then to call the method然后调用该方法

if(await CheckListForName("foo"))
   DoSomething();

or或者

var playerExistsTask = CheckListForName("foo"); //doesn't wait for task to finish here
Dothings();
bool playerExists = await playerExistsTask;//waits here

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

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