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
}
解决方案
这将是我解决您的问题的方法,即执行 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
}
如果您需要它更快,则需要将延迟除以相同数量的秒数
推荐阅读
- python - 在 DynamoDB 中插入多行 json
- java - BeanCreationException spring boot 和 keycloak
- php - Paginate WPQuery redirect to page 1
- python - Python - 查找字符串列表中包含的唯一子字符串的索引,而无需遍历所有项目
- java - private final Card[]cards, how do I use this in another class
- android - 应用更改失败时自动执行“运行”
- angular - Cannot find name 'cordova'. ionic 5 build android
- sql - osquery suid_bin 用于列出所有系统 suid 位集
- text-to-speech - Speech API OneCore 中的 Sayaka 语音在哪里?
- php - DomPdf - 修复了所有页面中的标题,但它与表格一起折叠