lunes, 30 de abril de 2007

Threading secuencial.

En estos días tuve un ligerillo problema con una aplicación que requeria una secuencia de acciones ejecutadas de forma secuencial pero en threads distintos. Aquí dejo un ejemplo que me hice y que me ayudo mucho:


using System;
using System.Threading;
using System.Collections.Generic;

namespace WindowsApplication1 {
class secuencialThread {
[STAThread]
static void Main(string[] args) {
threadSleep t = new threadSleep();
t.init();
}

}
public class threadSleep {
public Object esperaThread = "Que te esperes ...";
public Mutex firstMutex = new Mutex(false);
private Dictionary listadoThreads = new Dictionary();

public void init() {
this.listadoThreads.Add("Thread0", new Thread(new ParameterizedThreadStart(initThead)));
this.listadoThreads.Add("Thread1", new Thread(new ParameterizedThreadStart(initThead)));
this.listadoThreads.Add("Thread2", new Thread(new ParameterizedThreadStart(initThead)));
this.listadoThreads.Add("Thread3", new Thread(new ParameterizedThreadStart(initThead)));
this.listadoThreads.Add("Thread4", new Thread(new ParameterizedThreadStart(initThead)));

foreach (KeyValuePair item in this.listadoThreads) {
item.Value.Start(item.Key);
}
}

private void initThead(object data) {
lock (esperaThread) {
firstMutex.WaitOne();
Console.WriteLine("inicio de Thread --> " + (string)data);
for (int i = 0; i <= 5; i++) {
Console.WriteLine((string)data);
}
firstMutex.ReleaseMutex();
Console.WriteLine("Fin de Thread --> " + (string)data);
if ((string)data == "Thread4") {
Console.WriteLine("Fin de Threads" );
}

}
}
}
}

Esto produce como resultado:

inicio de thread Thread0 1,2,3,4,5 Fin de thread Thread0

inicio de thread Thread1 1,2,3,4,5 Fin de thread Thread1

inicio de thread Thread2 1,2,3,4,5 Fin de thread Thread2

inicio de thread Thread3 1,2,3,4,5 Fin de thread Thread3

inicio de thread Thread4 1,2,3,4,5 Fin de thread Thread4

Fin de Threads

2 comentarios:

  1. hola javier me parece una buena idea lo que hiciste... No lo dejes de hacer....

    ResponderEliminar
  2. Gracias, los comentarios, ideas y demás de otra gente ayuda a seguir.

    ResponderEliminar