Ver Mensaje Individual
  #1  
Antiguo 10-11-2014
JuanOrtega JuanOrtega is offline
Miembro
NULL
 
Registrado: sep 2011
Posts: 130
Reputación: 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