我创建了一个名为“Delay”的静态类,它基本上接受(double delay,ThreadStart action)的参数。这是:
public class Delay
{
public static void Execute(double delay, ThreadStart action)
{
Delay.Execute((int)delay, action);
}
public static void Execute(int delay, ThreadStart action)
{
Timer t = new Timer(delay);
t.Elapsed += new ElapsedEventHandler(delegate(object sender, ElapsedEventArgs e)
{
t.Stop();
action();
t.Dispose();
t = null;
});
t.Start();
}
private Timer t;
public Delay(int delay, ThreadStart action)
{
t = new Timer(delay);
t.Elapsed += new ElapsedEventHandler(delegate(object sender, ElapsedEventArgs e)
{
if (t != null)
{
t.Stop();
action();
t.Dispose();
}
t = null;
});
}
public void Execute()
{
t.Start();
}
public void Cancel()
{
if (t != null)
{
t.Stop();
t.Dispose();
}
t = null;
}
}
我有几个问题。
最好的问候。
答案 0 :(得分:4)
你不需要任何这些。只需你可以使用async / await功能:
public async Task Execute(double delay, ThreadStart action)
{
await Task.Delay((int)delay).ContinueWith((x) => action());
}