C#-等待条件为真的最佳方法 [英] C# – Best way to wait until a condition is true

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

问题描述

你好

从任务内部等待条件为真(最好是超时)的最佳方法是什么?
我的代码在Task中运行,并且我必须等待的标志来自库.
SipnWait可能是一个不错的选择吗?
谢谢

What is the best way to wait until a condition is True from inside a Task (possibly with a timeout)?
My code is running inside a Task and the flag that I must wait is from a library.
SipnWait can be a good choice?
Thank you

推荐答案

嗨ivan692007,

Hi ivan692007,

AFAIK,我建议您使用

AFAIK, I would suggest you 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<string> 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("Your work");
 }

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

只知道只有第一个Set()信号WaitOne()将等待,直到该信号在实施后继续.

最诚挚的问候,

克里斯汀


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

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