[英]How do you return a value that is dependent on the result of a co-routine that is started within the method? (C#)
我有一個返回布爾值的公共方法。 該方法啟動一個協同程序。 協程決定了 bool 的值。 我剛剛意識到該方法將在不等待協程完成的情況下返回 bool。 我對如何實現這一目標感到茫然。
一個例子。 假設一個單獨的類正在調用它:
public bool CheckListForName(string username)
{
StartCoroutine(DownloadPlayer(username));
return playerExists;
}
我意識到這段代碼在沒有上下文的情況下毫無意義,但是如果默認情況下將 bool "playerExists" 設置為 "False",但協程 "DownloadPlayer" 會發現 "playerExists" 實際上應該為真,這無關緊要,因為 " CheckListForName”將在協程找到正確值之前已經返回“false”。
我對編程比較陌生,所以非常感謝任何幫助!
您可能需要考慮使用 async/await
public async Task<bool> CheckListForName(string username)
{
await DownloadPlayer(username);
return playerExists;
}
然后調用該方法
if(await CheckListForName("foo"))
DoSomething();
或者
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.