C# .NET: Delay Timer To Pause Execution of a Function for 1 Second

10/12/2014 10:11:23 PM

The following can be used to delay the execution of a method in .NET. It does not require setting up a Timer object and delegate. It is simple and will take in a method and a time delay in milliseconds.

//method you want to call
public void DoSomething()
{
	//code to do something
}


//method to execute a delayed method
public async void DelayedExecute(Action action, int timeoutInMilliseconds)
{            
	await System.Threading.Tasks.Task.Delay(timeoutInMilliseconds);
	action();
}


//execute DoSomething in 1 second
DelayedExecute(DoSomething, 1000);