Torna al Thread
public partial class Form2 : Form
{
public delegate bool EndWavEventHandler(object sender, string Wav);
bool stop = false;
EndWavEventHandler endWavEventHandler = null;
public event EndWavEventHandler EndWav
{
add { this.endWavEventHandler += value; }
remove { this.endWavEventHandler -= value; }
}
public Form2()
{
InitializeComponent();
//aggiungo un handler di fine wav alla classe stessa (avrei potuto aggiungerlo in altra classe)
this.EndWav += new EndWavEventHandler(Form2_EndWav);
}
//questo metodo elabora la condizione e restituisce al chiamante un bool che stabilisce se continuare l'esecuzione
bool Form2_EndWav(object sender, string Wav)
{
//se è necessario l'invoke (necessario per modifiche di controlli chiamate da thred differente)
if (this.InvokeRequired)
//richiamo questo metodo con un delegato
return (bool)this.Invoke(new EndWavEventHandler(Form2_EndWav), sender, Wav);
// non è necessario l'invoke (chiamato da delegato)
else
{
//controllo se è stato premuto il bottone "Stop"
if (this.stop)
{
//scrivo ok nella label
this.label1.Text = "ok";
return true;
}
//non è stato premuto stop
return false;
}
}
private void button1_Click(object sender, EventArgs e)
{
//creo un nuovo thread
Thread t = new Thread(PlayWavAsyncForEndWav);
//avvio il thread con il codice per il play del wav
t.Start();
}
void PlayWavAsyncForEndWav()
{
string path = @"C:\Windows\Media\chimes.wav";
SoundPlayer simpleSound = new SoundPlayer(path);
bool _continue = true;
//continuo a ciclare e eseguire il wav finche l'evento non mi restituisce true;
while (_continue)
{
simpleSound.PlaySync();
if (this.endWavEventHandler != null)
//se mi restituisce true, il ciclo si ferma
_continue = !this.endWavEventHandler(this, path);
else
_continue = false;
}
//continuo con altro codice, in questo caso il tada!
simpleSound.SoundLocation = @"C:\Windows\Media\tada.wav";
simpleSound.PlaySync();
}
//bottone di stop, quando premuto ferma il ciclo del play
private void button2_Click(object sender, EventArgs e)
{
this.stop = !this.stop;
}
}