Skip to main content
The 2024 Developer Survey results are live! See the results
1 of 2
Evorlor
  • 1.6k
  • 2
  • 18
  • 23

Don't make a function that never returns. Don't ask the caller to put that function on its own thread.

Put the logic on its own thread within the function. Then name it appropriately for whever it does.

For example, in C#:

public void Foo()
{
    new Thread(() =>
    {
        while (true)
        {
            _player.Play("scary_sound.wav");
            Thread.Sleep(TimeSpan.FromMinutes(5));
        }
    }).Start();
}

However, as stated in other answers, an infinite loop is not the ideal way to go. Especially in this case, since the thread will never be killed. So maybe something like this would be more appropriate:

private static bool playSounds;
public void PlaySounds()
{
    playSounds = true;
    new Thread(() =>
    {
        while (playSounds)
        {
            _player.Play("scary_sound.wav");
            Thread.Sleep(TimeSpan.FromMinutes(5));
        }
    }).Start();
}

public void StopSounds()
{
    playSounds = false;
}
Evorlor
  • 1.6k
  • 2
  • 18
  • 23