How to delay an action or keep on a timed loop C#

Key phrases: Repeating code on delay, pause without thread sleep, delaying code

c#

Usage: var dir = Directory.GetCurrentDirectory();

var file = SoundByName(sound);

var actual = Path.Combine(dir, file);

SoundPlayer player = new SoundPlayer(actual);

player.Play();

if (milliseconds > 0) { DelayFactory.DelayAction(milliseconds, () => player.Stop()); }

DelayFactory.DelayActionRepeat(milliseconds, () => player.Stop());

Code:
namespace ALineOfCode.Community.AugmentedLibraries.Common.Factory
{
public static class DelayFactory
{
public static void DelayAction(int millisecond, Action action)
{
var timer = new DispatcherTimer();
timer.Tick += delegate
{
DispatcherHelper.CheckBeginInvokeOnUI(async () =>
{
action.Invoke();
timer.Stop();
});
};
timer.Interval = TimeSpan.FromMilliseconds(millisecond);
timer.Start();
}

public static void DelayActionRepeat(int millisecond, Action action)
{
var timer = new DispatcherTimer();
timer.Tick += delegate
{
DispatcherHelper.CheckBeginInvokeOnUI(async () =>
{
action.Invoke();
});
};
timer.Interval = TimeSpan.FromMilliseconds(millisecond);
timer.Start();
}
}
}

Share on Facebook

Leave a Reply

Your email address will not be published. Required fields are marked *