views:

58

answers:

1

Hi all,

I'll try explain me as better possible, sorry my english.

I have a Thread, within this thread I call method, which have long time process.

The method has a foreach, and using counter for each iteration (counter++)

I want to do this:

a). Within foreach, if counter > 20:

a1). Check if any proccess (which Name = "SendMailService.exe") is executing.

a2). If NOT executing process, do this: launch using process.start(sendmailservice.exe);

a3). If executing the process, check again (step a1) each 3 minutes.

b.) After the foreach code:

b1). Check if any proccess (which Name = "SendMailService.exe") is executing.

b2). If is executing process, wait until the process finished.

Anybody can understand me? any help will be appreciated.

Thanks in advanced, greetings, happy new year

My code is:

private void bEnviarAleatorioSeleccionados_Click(object sender, EventArgs e)
{
    CrossThreadCalls();

    this.bEnviarAleatorioSeleccionados.Enabled = false;

    Thread hiloMain = new Thread(new ThreadStart(EnviarAleatorioSeleccionadosYEnviarCorreo)); // Threads werden erzeugt
    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;
}
A: 

Well, two things:

Since you're doing this on a separate thread anyways:

// DO THE CHECK HERE, EACH 3 MINUTES (TIMER) !!!! HOW ???????? 
if (contador > 20)  { ... }

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.Exited event, 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).

Reed Copsey
I want block the thread, using Thread.Sleep(180000); I'll test Process.Exited, I'll find any sample code. Thanks mister. Happy new year.