首页 > 解决方案 > 通过特定时间检查字符串值

问题描述

我想检查指定时间的字符串值。我设置了。在此期间,您将按下按钮来更改字符串的值并实现条件。如果您在指定时间内没有按下按钮,您将不会检查状态。如果时间结束,条件将不成立。使用此代码时,始终满足条件:(:

string value;
private void button3_Click(object sender, EventArgs e)
{
    IAsyncResult result;
     Action action  = () => 
     {
         do //loop to check value through 10s
         {
            return;
         }
         while ( value == "");              
     };
     result = action.BeginInvoke(null, null);
     if(result.AsyncWaitHandle.WaitOne(10000)) 
                  //wait 10s to check response
    {
         listBox2.Items.Add("good"); // if response string value != ""
    }
    else 
    {
         listBox2.Items.Add("bad"); 
              // if response string value == "" or timeout  
    }
}

private void button4_Click(object sender, EventArgs e)
{
    value = "best"; // add value
}

标签: c#

解决方案


这将是我解决您的问题的方法,即执行 while 循环,老实说不会有任何好处

    string value;
    private void button3_Click(object sender, EventArgs e)
    {
        WaitSecondsAndExecute(10);

    }

    private async void WaitSecondsAndExecute(int seconds)
    {
        for (int i = 0; i < seconds; i++)
        {
            await Task.Delay(1000);
            if (value != null)
            {
                break;
            }
        }

        if (value != null)
        {
            listBox2.Items.Add("good"); // if response string value != ""
        }
        else
        {
            listBox2.Items.Add("bad");
            // if response string value == "" or timeout  
        }
    }

    private void button4_Click(object sender, EventArgs e)
    {
        value = "best"; // add value
    }

如果您需要它更快,则需要将延迟除以相同数量的秒数


推荐阅读