revolutionkpi
revolutionkpi

Reputation: 2682

How to invoke some method in some time (500 millisecond ) in SilverLight

I have two methods, for example Method1 and Method2. How can I invoke Method2 500ms after Method1 completes?

 public void Method1()
 {

 }

 public void Method2()
 {

 }

Upvotes: 2

Views: 4172

Answers (3)

iCollect.it Ltd
iCollect.it Ltd

Reputation: 93561

Use either the Timer or a BackgroundWorker. Timer is probably most appropriate for your brief description unless you want to do something on the UI thread in which case a DispatchTimer is better for you as it calls back on the UI thread.

Example:

  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
  }

Upvotes: 7

syedmoulaali
syedmoulaali

Reputation: 41

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


}

Upvotes: 0

Phil Degenhardt
Phil Degenhardt

Reputation: 7264

Task.Factory.StartNew( () => 
{
    Methdd1();
    Thread.Sleep(500);
    Method2();
});

EDIT

Due to the issue highlighted by @spender this code is problematic and could lead to thread starvation (see: http://msdn.microsoft.com/en-us/library/ff963549.aspx). The timer suggested by @HiTech Magic seems a better way to go.

Upvotes: 1

Related Questions