1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
|
namespace Test
{
class Program
{
static void Main(string[] args)
{
DoWork test = new DoWork();
}
}
class DoWork
{
private String ActionTodo = "nothing";
Thread ActionThread;
bool stopThread = false;
//Constructeur
public DoWork()
{
ActionThread = new Thread(ActionLoop);
ActionThread.IsBackground = true;
ActionThread.Start();
//...ici un tas d'action
//puis premiere demande d'action
ActionTodo = "coucou";
Thread.Sleep(60); //Tempo de 60 pour etre sur que mon nombre soit traité dans l'ActionLoop
//...ici un tas d'action
//puis deuxieme demande d'action
ActionTodo = "bonjour";
Thread.Sleep(60);
//...ici un tas d'action
//puis troisieme demande d'action
ActionTodo = "youpie";
Thread.Sleep(60);
//...ici un tas d'action
//puis quatrieme demande d'action qui n'existe pas
ActionTodo = "foo";
Thread.Sleep(60);
//puis cinquieme demande d'action
ActionTodo = "cava";
Thread.Sleep(60);
//...ici un tas d'action
//puis derniere demande d'action
ActionTodo = "byebye";
Thread.Sleep(60);
Console.ReadKey();
stopThread = true;
}
public void ActionLoop()
{
while (!stopThread) //On tourne tant que l'on arrete pas le programme
{
Random rand = new Random();
int tempo = 0;
//On teste la valeur de ActionTodo
switch (ActionTodo)
{
case "coucou":
tempo = rand.Next(200); //temporisation arbitraire simulant un temps de traitement variable...
Console.WriteLine("Coucou (" + tempo +"ms)");
Thread.Sleep(tempo);
break;
case "bonjour":
tempo = rand.Next(200);
Console.WriteLine("Bonjour(" + tempo + "ms)");
Thread.Sleep(tempo);
break;
case "youpie":
tempo = rand.Next(200);
Console.WriteLine("Youpie(" + tempo + "ms)");
Thread.Sleep(tempo);
break;
case "cava":
tempo = rand.Next(200);
Console.WriteLine("Ca va ? (" + tempo + "ms)");
Thread.Sleep(tempo);
break;
case "byebye":
tempo = rand.Next(200);
Console.WriteLine("Au Revoir(" + tempo + "ms)");
Thread.Sleep(tempo);
break;
case "nothing":
default: break;
}
//On remet ActionToDo à "nothing" pour éviter de tourner en boucle sur la meme action
ActionTodo = "nothing";
Thread.Sleep(50);
}
}
}
} |
Partager