我有两种方法,例如Method1和Method2。在Method1完成后如何调用Method2 500ms?
public void Method1()
{
}
public void Method2()
{
}
答案 0 :(得分:6)
使用Timer或BackgroundWorker。除非你想在UI线程上做一些事情,否则Timer可能最适合你的简短描述,在这种情况下DispatchTimer更适合你,因为它在UI线程上回调。
public void Run_Method1_Then_Method2_500_Milliseconds_Later()
{
DispatcherTimer timer = new DispatcherTimer();
timer.Interval = TimeSpan.FromMilliseconds(500);
timer.Tick += (s, e) =>
{
// do some quick work here in Method2
Method2(timer);
};
Method1(); // Call Method1 and wait for completion
timer.Start(); // Start Method2 500 milliseconds later
}
public void Method1()
{
// Do some work here
}
public void Method2(DispatcherTimer timer)
{
// Stop additional timer events
timer.Stop();
// Now do some work here
}
答案 1 :(得分:1)
Task.Factory.StartNew( () =>
{
Methdd1();
Thread.Sleep(500);
Method2();
});
修改强>
由于@spender突出显示此问题,此代码存在问题,可能导致线程不足(请参阅:http://msdn.microsoft.com/en-us/library/ff963549.aspx)。 @HiTech Magic建议的计时器似乎是一个更好的方法。
答案 2 :(得分:0)
System.Timers.Timer aTimer = new System.Timers.Timer(10000);
// Hook up the Elapsed event for the timer.
aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
// Set the Interval to 60 seconds (60000 milliseconds).
aTimer.Interval = 60000;
//for enabling for disabling the timer.
aTimer.Enabled = false;
private void OnTimedEvent(object source, ElapsedEventArgs e)
{
//disable the timer
aTimer.Enabled = false;
Method2();
}
public void Method1()
{
//some code
aTimer.Enabled = true;
}
public void Method2()
{
}