Supposons que ThreadA et ThreadB appellent tous deux WaitOne()
dans cet ordre sur le même AutoResetEvent. Lorsque l'événement est défini, pourquoi ThreadB est-il libéré au lieu de ThreadA?Pourquoi le deuxième thread est-il publié avant le premier, quand ils ont tous deux appelé WaitOne() et ont été libérés par un AutoResetEvent?
J'ai couru un test pour savoir ce qui se passe lorsque vous définissez un AutoResetEvent sur lequel mutiple threads attendent:
private static void Test()
{
// two threads - waiting for the same autoreset event
// start it unset i.e. closed i.e. anything calling WaitOne() will block
AutoResetEvent autoEvent = new AutoResetEvent(false);
Thread thread1 = new Thread(new ThreadStart(WriteSomeMessageToTheConsole));
thread1.Start(); // this will now block until we set the event
Thread thread2 = new Thread(new ThreadStart(WriteSomeOtherMessageToTheConsole));
thread2.Start(); // this will now also block until we set the event
// simulate some other stuff
Console.WriteLine("Doing stuff...");
Thread.Sleep(5000);
Console.WriteLine("Stuff done.");
// set the event - I thought this would mean both waiting threads are allowed to continue
// BUT thread2 runs and thread1 stays blocked indefinitely
// So I guess I was wrong and that Set only releases one thread in WaitOne()?
// And why thread2 first?
autoEvent1.Set();
}
Le code est bien sûr pas utile; c'est juste un exemple de souris mickey. Et ce n'est pas important/urgent. Mais je serais intéressé à en savoir plus quand même ...
Essayez d'appeler autoEvent1.Set(); encore une fois pour voir si l'autre thread sera libéré. Je pense que vous devez tourner l'interrupteur deux fois. –
Salut - oui J'ai essayé tout de suite après - je peux obtenir le deuxième fil pour continuer avec un second appel à Set() - mais seulement si j'introduis un délai par exemple. avec un appel à Thread.Sleep(). –
Je suis actuellement plus intéressé de voir si quelqu'un sait réellement que le fil qui est libéré est aléatoire. La documentation indique que les threads sont mis en file d'attente en indiquant une sorte d'ordre (c'est pourquoi je m'attendais à ce que le premier thread soit publié en premier). –