Aishvarya Jaiswal
Aishvarya Jaiswal

Reputation: 1811

How to run a function after a specific time

I want to as if there is any way to execute a function after a specific time in windows phone 7.? For instance, see this code in android:

mRunnable=new Runnable() 
{

@Override
public void run() 
 {
 // some work done
}

now another function

public void otherfunction()
{
mHandler.postDelayed(mRunnable,15*1000);
}

Now the work done in upper code will be executed after 15 seconds of execution of otherfunction(). And I want to know is this possible in any way in windows phone 7 also.? Thanx to all in advance..

Upvotes: 0

Views: 185

Answers (3)

Igor Kulman
Igor Kulman

Reputation: 16361

No need for creating threads. This can be done much more easier using Reactive Extensions (reference Microsoft.Phone.Reactive):

Observable.Timer(TimeSpan.FromSeconds(15)).Subscribe(_=>{
    //code to be executed after two seconds
});

Beware that the code will not be executed on the UI thread so you may need to use the Dispatcher.

Upvotes: 0

Jim Mischel
Jim Mischel

Reputation: 134105

Although you can use the Reactive Extensions if you want, there's really no need. You can do this with a Timer:

// at class scope
private System.Threading.Timer myTimer = null;


void SomeMethod()
{
    // Creates a one-shot timer that will fire after 15 seconds.
    // The last parameter (-1 milliseconds) means that the timer won't fire again.
    // The Run method will be executed when the timer fires.
    myTimer = new Timer(() =>
        {
            Run();
        }, null, TimeSpan.FromSeconds(15), TimeSpan.FromMilliseconds(-1));
}

Note that the Run method is executed on a thread pool thread. If you need to modify the UI, you'll have to use the Dispatcher.

This method is preferred over creating a thread that does nothing but wait. A timer uses very few system resources. Only when the timer fires is a thread created. A sleeping thread, on the other hand, takes up considerably more system resources.

Upvotes: 1

Kevin Gosse
Kevin Gosse

Reputation: 39027

You can do that by using threads:

var thread = new Thread(() =>
    {
        Thread.Sleep(15 * 1000);
        Run();
    });

thread.Start();

This way, the Run method wil be executed 15 seconds later.

Upvotes: 1

Related Questions