Club Delphi  
    FTP   CCD     Buscar   Trucos   Trabajo   Foros

Retroceder   Foros Club Delphi > Principal > Varios
Registrarse FAQ Miembros Calendario Guía de estilo Temas de Hoy

Grupo de Teaming del ClubDelphi

 
 
Herramientas Buscar en Tema Desplegado
  #1  
Antiguo 10-11-2014
JuanOrtega JuanOrtega is offline
Miembro
NULL
 
Registrado: sep 2011
Posts: 130
Poder: 13
JuanOrtega Va por buen camino
Ejecutar multiples archivos con Threads

Hola estaba tratando de traducir un codigo de c# a delphi donde se podian crear multiples threads sin tener que hacerlos a mano con eso me refiero a que era un bucle que los iba creando no hacerlos uno por uno , en principio tenia este codigo :

Código Delphi [-]
program Project1;

{$APPTYPE CONSOLE}
{$R *.res}

uses
  System.SysUtils, ShellApi,Windows;

var
  i: integer;

const
  files: array [1 .. 7] of string = ('file1.exe', 'file2.exe', 'file3.exe',
    'file4.exe', 'file5.exe', 'file6.exe', 'file7.exe');

begin
  try
    begin

      for i := Low(files) to High(files) do
      begin
        Writeln(files[i]);
        ShellExecute(0, 'open', PChar(files[i]), nil, nil,SW_SHOWNORMAL);
      end;
    end;

  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;

end.

Mi plan principal era ejecutar varios archivos al mismo tiempo con threads como lo muestro en el bucle con shellexecute , el tema es que guiandome con los ejemplos de threads que encontre en delphipages

Código Delphi [-]
program Project1;

{$APPTYPE CONSOLE}

uses
Classes, SysUtils;

type

TThreadEx = class(TThread)
  protected
    procedure Execute;override;
end;

{ TThreadEx }

procedure TThreadEx.Execute;
begin
  While not terminated do
  begin
    Writeln(threadId, ' : running...');
    Sleep(1000 + random(1000)) ;
  end;
end;

var thread1, thread2: TThreadEx;
begin
  Writeln('starting threads, press any key to stop');
  thread1 := TThreadEx.Create(false);
  thread2 := TThreadEx.Create(false);
  readln;
  Writeln('stopping threads...');
  thread1.Terminate;
  thread2.Terminate;
  thread1.WaitFor;
  thread2.WaitFor;
  Writeln('Done.');
  readln;
end.

Me hicieron dar cuenta de que era imposible hacerlo en delphi , pregunte en stackoverflow y me recomendaron el
componente OmniThread pero queria preguntarles aca si alguien conocia otra forma que no sea usar componentes de
terceros porque quiero generar la minimo dependencia en el programa consola final.

El codigo en c# que inspiro esta idea rara es este :

Código Delphi [-]
private void btnCheck_Click(object sender, EventArgs e)
{
    Working = 0;
    Broken = 0;
    Timeout = Convert.ToInt32(txtTimeout.Text);
    string[] Lines = txtInputProxies.Lines;
    prgProgress.Maximum = Lines.Length;

    for (int i = 0; i < Lines.Length; i++)
    {
       new Thread(
          delegate(object o)
          {
             try
             {
                string[] Proxy = ((string)o).Split(':');
                WebRequest req = WebRequest.Create("http://google.nl");
                req.Proxy = new WebProxy(Proxy[0], Convert.ToInt32(Proxy[1]));
                req.Timeout = Timeout;
                req.GetResponse();
                UpdateStatus(true, string.Join(":", Proxy));
             }
             catch
             {
                UpdateStatus(false, "");
             }
          }).Start(Lines[i]);
    }
}

private void UpdateStatus(bool goodProxy, string Proxy)
{
   Invoke(new MethodInvoker(
   delegate()
   {
      prgProgress.Value++;
      if (goodProxy)
      {
         txtWorkingProxies.Text += Proxy + Environment.NewLine;
         lblWorking.Text = "Working: " + (++Working).ToString();
      }
      else
      {
         lblBroken.Text = "Broken: " + (++Broken).ToString();
      }
      lblTotal.Text = "Total: " + (Broken + Working).ToString();
    }));
}

¿ Alguien me puede ayudar ?

Última edición por JuanOrtega fecha: 10-11-2014 a las 22:05:27.
Responder Con Cita
 



Normas de Publicación
no Puedes crear nuevos temas
no Puedes responder a temas
no Puedes adjuntar archivos
no Puedes editar tus mensajes

El código vB está habilitado
Las caritas están habilitado
Código [IMG] está habilitado
Código HTML está deshabilitado
Saltar a Foro

Temas Similares
Tema Autor Foro Respuestas Último mensaje
Ejecutar programa en el Inicio con Múltiples sesiones y/o servidor gluglu Varios 3 13-01-2013 12:48:38
error copiando multiples archivos jonydread API de Windows 13 14-08-2012 08:52:35
Agregar múltiples Campo de una tabla a múltiples TEdit y TdbEdit novato_erick Varios 21 21-08-2011 01:18:58
Uno o multiples archivos luis.gutierrez API de Windows 4 06-04-2010 18:51:24
Open dialog y multiples archivos b2k Varios 3 16-09-2007 23:22:37


La franja horaria es GMT +2. Ahora son las 01:26:37.


Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2024, Jelsoft Enterprises Ltd.
Traducción al castellano por el equipo de moderadores del Club Delphi
Copyright 1996-2007 Club Delphi