[英]Create a countdown timer on a event
我想在每次if
语句为true
时创建一个新的倒数计时器,它应该像这样工作:
例如:
List<int> intList = new List<int>();
foreach(a in b)
{
if(a==1)
{
intList.Add(a.somevalue)
//should create a new countdown timer for 1 hour and once the time is finished, it
should remove the added value from the list
}
}
我如何实现这一目标?
谢谢。
好吧,首先,我们真的不应该从不同的线程修改List
,所以这使我们能够确保所有定时事件通过单个线程,或者应用它们自己的某种同步,或者我们使用不同的数据结构,从多个线程使用没有问题。
至于实际上在一小时内做什么,虽然你可以使用一个Timer
,但Task.Delay
非常适合这里:
List<int> list = new List<int>();
object key = new object();
foreach (int a in b)
if (a == 1)
{
var value = GetValue(a);
list.Add(value);
Task.Delay(TimeSpan.FromHours(1))
.ContinueWith(t => { lock (key)list.Remove(value); });
}
最简单的答案:
var value = a.someValue;
new Thread(() => { Thread.Sleep(60 * 60 * 1000); intList.Remove(value); }).Start();
但实际上你会想要保存线程引用,以便以后可以在需要时中断它。 特别是如果有后台线程运行,你的程序将不会退出。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.