如何在SilverLight中在一段时间(500毫秒)内调用某个方法

本文关键字:调用 方法 SilverLight 一段时间 500毫秒 | 更新日期: 2023-09-27 18:27:12

我有两个方法,例如Method1和Method2。如何在Method1完成后调用Method2 500ms?

 public void Method1()
 {
 }
 public void Method2()
 {
 }

如何在SilverLight中在一段时间(500毫秒)内调用某个方法

使用Timer或BackgroundWorker。Timer可能最适合您的简短描述,除非您想在UI线程上做一些事情,在这种情况下,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
  }
Task.Factory.StartNew( () => 
{
    Methdd1();
    Thread.Sleep(500);
    Method2();
});

编辑

由于@spender强调的问题,此代码存在问题,可能导致线程饥饿(请参阅:http://msdn.microsoft.com/en-us/library/ff963549.aspx)。@HiTech Magic建议的计时器似乎是一个更好的选择。

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()
{

}