C# Wait until condition is true

后端 未结 7 1597
暖寄归人
暖寄归人 2020-12-24 05:52

I am trying to write a code that executes when a condition is met. Currently, I am using while...loop, which I know is not very efficient. I am also looking at AutoResetEven

7条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-24 06:10

    You can use an async result and a delegate for this. If you read up on the documentation it should make it pretty clear what to do. I can write up some sample code if you like and attach it to this answer.

    Action isExcelInteractive = IsExcelInteractive;
    
    private async void btnOk_Click(object sender, EventArgs e)
    {
        IAsyncResult result = isExcelInteractive.BeginInvoke(ItIsDone, null);
        result.AsyncWaitHandle.WaitOne();
        Console.WriteLine("YAY");
    } 
    
    static void IsExcelInteractive(){
       while (something_is_false) // do your check here
       {
           if(something_is_true)
              return true;
       }
       Thread.Sleep(1);
    }
    
    void ItIsDone(IAsyncResult result)
    {
       this.isExcelInteractive.EndInvoke(result);
    }
    

    Apologies if this code isn't 100% complete, I don't have Visual Studio on this computer, but hopefully it gets you where you need to get to.

提交回复
热议问题