c# how to pause between 2 function calls without stopping main thread
Foo();
Foo(); // i want this to run after 2 min without stopping main thread
Function Foo()
{
}
Thanks
c# how to pause between 2 function calls without stopping main thread
Foo();
Foo(); // i want this to run after 2 min without stopping main thread
Function Foo()
{
}
Thanks
Try:
Task.Factory.StartNew(() => { foo(); })
.ContinueWith(t => Thread.Sleep(2 * 60 * 1000))
.ContinueWith(t => { Foo() });
Task.Factory.StartNew(Foo)
.ContinueWith(t => Task.Delay(TimeSpan.FromMinutes(2)))
.ContinueWith(t => Foo());
Please, do not sleep on thread pool. Never
"There are only a limited number of threads in the thread pool; thread pools are designed to efficiently execute a large number of short tasks. They rely on each task finishing quickly, so that the thread can return to the pool and be used for the next task." More here
Why Delay
? It uses DelayPromise
internally with a Timer
, it's efficient, way more efficient
How about using a Timer
:
var timer = new Timer();
timer.Interval = 120000;
timer.Tick += (s, e) =>
{
Foo();
timer.Stop();
}
timer.Start();
Try spawning a new thread, like so:
new Thread(() =>
{
Foo();
Thread.Sleep(2 * 60 * 1000);
Foo();
}).Start();
You can use a Timer Class.
using System;
using System.Timers;
public class Timer1
{
private static System.Timers.Timer aTimer;
public void Foo()
{
}
public static void Main()
{
Foo();
// Create a timer with a two minutes interval.
aTimer = new System.Timers.Timer(120000);
// Hook up the Elapsed event for the timer.
aTimer.Elapsed += new ElapsedEventHandler(Foo());
aTimer.Enabled = true;
}
// Specify what you want to happen when the Elapsed event is
// raised.
private static void OnTimedEvent(object source, ElapsedEventArgs e)
{
Foo();
}
}
The code has not been tested.
var testtask = Task.Factory.StartNew(async () =>
{
Foo();
await Task.Delay(new TimeSpan(0,0,20));
Foo();
});