C#等到条件为真 [英] C# Wait until condition is true

查看:295
本文介绍了C#等到条件为真的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写满足条件的代码.目前,我正在使用while ... loop,我知道这不是很有效.我也在看AutoResetEvent(),但是我不知道如何实现它,以便它一直检查直到条件为真.

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 AutoResetEvent() but i don't know how to implement it such that it keeps checking until the condition is true.

代码也恰好存在于异步方法中,所以某种等待可能有效吗?

The code also happens to live inside an async method, so may be some kind of await could work?

private async void btnOk_Click(object sender, EventArgs e)
{
        // Do some work
        Task<string> task = Task.Run(() => GreatBigMethod());
        string GreatBigMethod = await task;

        // Wait until condition is false
        while (!isExcelInteractive())
        {
            Console.WriteLine("Excel is busy");
        }

        // Do work
        Console.WriteLine("YAY");
 }


    private bool isExcelInteractive()
    {
        try
        {
            Globals.ThisWorkbook.Application.Interactive = Globals.ThisWorkbook.Application.Interactive;
            return true; // Excel is free
        }
        catch
        {
            return false; // Excel will throw an exception, meaning its busy
        }
    }

我需要找到一种方法来继续检查isExcelInteractive()而不会导致CPU陷入循环.

I need to find a way to keep checking isExcelInteractive() without CPU stuck in a loop.

注意:Excel中没有处于未处于编辑模式时的事件处理程序.

Note: There is no event handler in Excel that would be raised when it is not in edit mode.

推荐答案

至少您可以将循环从繁忙等待更改为慢速轮询.例如:

At least you can change your loop from a busy-wait to a slow poll. For example:

    while (!isExcelInteractive())
    {
        Console.WriteLine("Excel is busy");
        await Task.Delay(25);
    }

这篇关于C#等到条件为真的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆