I have a thread, within this thread I call a method which takes a long time to process.
The method has a foreach using a counter for each iteration (counter++)
I want to do this:
- Within
foreach, if counter > 20:- Check if any proccess with name = “SendMailService.exe” is executing.
- If NOT executing, launch using
process.start(sendmailservice.exe); - If executing wait 3 minutes and then check again.
- After the foreach code
- Check if any proccess with name = “SendMailService.exe” is executing.
- If process is executing, wait until the process finished.
Anybody can understand me? any help will be appreciated.
My code is:
private void bEnviarAleatorioSeleccionados_Click(object sender, EventArgs e)
{
CrossThreadCalls();
this.bEnviarAleatorioSeleccionados.Enabled = false;
// Threads werden erzeugt
Thread hiloMain = new Thread(
new ThreadStart(EnviarAleatorioSeleccionadosYEnviarCorreo));
hiloMain.Start(); // Threads werden gestartet
}
private void EnviarAleatorioSeleccionadosYEnviarCorreo()
{
string rutaFicheroMp3 = GetRutaFicheroMp3DeLoquendo(textoLoquendo);
int contador = 0;
foreach (ListViewItem item in lstRecientes.Items)
{
if (item.Checked)
{
contador++;
EnviarCorreoParaElementoListView(item, rutaFicheroMp3, item.Text);
}
// DO THE CHECK HERE, EACH 3 MINUTES (TIMER) !!!! HOW ????????
if (contador > 20)
{
var listaP = Process.GetProcesses().FirstOrDefault(
p => p.ProcessName == "ServicioEnvioCorreo.exe");
if (listaP == null)
{
// Iniciar Envio de Correo
EnviarCorreosPorProceso();
}
}
}
EliminarFicheroLoquendo(rutaFicheroMp3);
this.bEnviarAleatorioSeleccionados.Enabled = true;
}
Well, two things:
Since you’re doing this on a separate thread anyways:
You could easily just block the thread for your 3 minute check, instead of using a timer. A simple
Thread.Sleep(180000);will put a 3 minute delay into your loop.That being said, I’d question whether this is really the best approach to this problem. Since you’re starting the process yourself, you could attach a handler to the
Process.Exitedevent, and “restart” the process after it exits. This would eliminate the entire need for the loops, checks, and probably even the entire separate thread. Just start the process, and when it exists, restart it (20x).