等待方法返回true

Roc*_*ngh 1 .net c# asp.net c#-4.0

我有两个方法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
    }
Run Code Online (Sandbox Code Playgroud)

我希望A方法等待并且不执行"var xx ="test";" 行除非B方法返回true.你能指点一下如何帮助我吗?

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

Pat*_*ick 6

你应该使用while循环

while (!B ()) { }
var x = "test";
Run Code Online (Sandbox Code Playgroud)

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

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

  • 特别是+1表示将事件作为更好的选择.此外,如果您需要注释来指出空语句,那么使用`{}`可能会更好. (2认同)