I saw similar questions, but none seemed to answer mine.
I'm trying to understand threads in general but just using C# to explore them.
So I have this in my main():
var sp = new SongPlayer();
sp.Play(path);
And the Play function looks like this:
public void Play(string path)
{
if (path.EndsWith("mp3"))
songThread = new System.Threading.Thread(() => PlayMp3(path));
else if (path.EndsWith("wav"))
songThread = new System.Threading.Thread(() => PlayWav(path));
songThread.Start();
songThread.Join();
}
(songThread is System.Threading.Thread type)
Could someone explain to me what exactly is happening behind the scenes?
If I add a breakpoint and step through, when I execute songThread.Join() then the mp3 starts playing. I'm guessing it doesn't start playing after calling Start() because control flow is still within the main thread. If I don't have the Join statement but instead do Thread.Sleep() then also the child thread executes, but my question is about the Join. It says the Join Blocks the calling thread until the current thread terminates. But when I trace through it just starts playing the mp3 and control flow keeps going in the main thread as well. So what does it mean it blocks the main thread, it's clearly not doing that...
Second, if I add another sp.Play(path2) right after the first one, then executing that stops the first one and starts the second one. What exactly is happening here? Is it C# doing memory management and killing off the first thread when I execute the Join on the second thread? Because I'm assigning to the same variable? Why would it not play them in parallel?
Thanks
First off, there's no real point in creating a new thread just to Join on it right away, in pretty much all cases. You might as well just do whatever action you would have done in the original thread; it'll do the same thing without taking the time to perform the very expensive work of creating, managing, and tearing down a thread.
As for why your program continues on despite the Join, that's because your PlayMp3 and PlayWav methods are asynchronous. They start playing the music, but those methods don't block until the song is done; they return almost immediately. Because they return, the thread finishes pretty much right away, so your Join method returns pretty much right away. If your threads were doing work that actually took a considerable amount of time, then you would see Join waiting for it to finish.
As for why subsequent calls to Play stops the previous songs, it has nothing at all to do with the code shown here. It would appear that your PlayMp3 and PlayWav methods are designed such that if they are called when another song is still playing that they will stop those songs. It has nothing to do with the code you've shown.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With