通过特定时间检查字符串值

时间:2018-11-01 13:05:13

标签: c#

我想检查指定时间的字符串值。我设置在这段时间内,您将按下按钮来更改字符串的值并达到条件。如果您在指定时间内未按按钮,则不会检查条件。如果时间结束,将无法满足条件。使用此代码时,条件始终满足:(:

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
}

1 个答案:

答案 0 :(得分:0)

这将是我解决您的问题的方法,而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
    }

如果您需要更快,只需将延迟除以秒并乘以相同的数量即可。