gpt4 book ai didi

c# - 等待方法返回 true

转载 作者:太空宇宙 更新时间:2023-11-03 17:52:25 25 4
gpt4 key购买 nike

我有两个方法 A 和 B。A 从内部调用 B 方法。 B 方法返回 true 或 false 文件是否有内容。这是代码:

    public static void A()
{
var isValid = B();
// Wait until "isValid" comes true
var xx = "test";
}

public static bool B()
{
// This will check for a file content
// Say C://test.txt
// If the file has some content this method will return true else false
}

我希望 A 方法等待并且不执行 "var xx = "test";"行,除非 B 方法返回 true。你能帮我指点一下怎么做吗?

编辑:我不能简单地使用 if 循环,即 if(isValid),因为要检查其内容的文件是由其他线程编写的,所以我需要从 A 内部不断检查 B 方法。我可以' t 让这段代码 "var xx = "test";"要执行,除非 B 返回 true,如果它返回 false,代码应该在那里等待(在 var isValid = B();),除非 B 返回 true,即代码应该持续检查 B 状态。

最佳答案

你应该使用 while 循环

while (!B ()) { }
var x = "test";

这将执行 B 直到它返回 true。更好的方法可能是实现一个事件,该事件将在条件变为真时触发。

考虑到您正在使用文件,您可以查看 FileSystemWatcher,它可以在文件更改时触发一个方法。

关于c# - 等待方法返回 true,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20743795/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com