C# Wait until condition is true

后端 未结 7 1620
暖寄归人
暖寄归人 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:16

    You can use thread waiting handler

    private readonly System.Threading.EventWaitHandle waitHandle = new System.Threading.AutoResetEvent(false);
    private void btnOk_Click(object sender, EventArgs e)
    {
        // Do some work
        Task task = Task.Run(() => GreatBigMethod());
        string GreatBigMethod = await task;
    
        // Wait until condition is false
        waitHandle.WaitOne();
        Console.WriteLine("Excel is busy");
        waitHandle.Reset();
    
        // Do work
        Console.WriteLine("YAY");
     }
    

    then some other job need to set your handler

    void isExcelInteractive()
    {
       /// Do your check
       waitHandle.Set()
    }
    

    Update: If you want use this solution, you have to call isExcelInteractive() continuously with specific interval:

    var actions = new []{isExcelInteractive, () => Thread.Sleep(25)};
    foreach (var action in actions)
    {                                      
        action();
    }
    

提交回复
热议问题