2017-04-21 21:04:03 +00:00
|
|
|
|
using System;
|
|
|
|
|
using System.Collections.Generic;
|
|
|
|
|
using System.Linq;
|
|
|
|
|
using System.Net.Sockets;
|
|
|
|
|
using System.Text;
|
|
|
|
|
using System.Threading;
|
|
|
|
|
|
2017-04-27 20:44:30 +00:00
|
|
|
|
namespace Kneesocks {
|
|
|
|
|
public class Stack<T> where T : Connection {
|
2017-04-24 21:04:52 +00:00
|
|
|
|
private Pool<T> PoolRef = null;
|
2017-04-21 21:04:03 +00:00
|
|
|
|
private List<Connection> Clients = new List<Connection>();
|
|
|
|
|
private Mutex ClientsMutex = new Mutex();
|
|
|
|
|
private bool RunWithNoClients = false;
|
2017-04-24 21:04:52 +00:00
|
|
|
|
private bool Running = true;
|
|
|
|
|
private bool _finished = false;
|
2017-04-21 21:04:03 +00:00
|
|
|
|
|
2017-04-24 21:04:52 +00:00
|
|
|
|
public Stack(Pool<T> poolRef, Connection initialConnection = null) {
|
|
|
|
|
PoolRef = poolRef;
|
2017-04-21 21:04:03 +00:00
|
|
|
|
if(initialConnection != null)
|
|
|
|
|
Clients.Add(initialConnection);
|
|
|
|
|
}
|
|
|
|
|
|
2017-04-24 21:04:52 +00:00
|
|
|
|
public Stack(Pool<T> poolRef, bool runWithNoClients, Connection initialConnection = null)
|
|
|
|
|
: this(poolRef, initialConnection)
|
2017-04-21 21:04:03 +00:00
|
|
|
|
{
|
|
|
|
|
RunWithNoClients = runWithNoClients;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public bool AddClient(Connection client) {
|
|
|
|
|
if(!ClientsMutex.WaitOne(5000))
|
|
|
|
|
return false;
|
|
|
|
|
|
|
|
|
|
Clients.Add(client);
|
|
|
|
|
|
|
|
|
|
ClientsMutex.ReleaseMutex();
|
|
|
|
|
return true;
|
|
|
|
|
}
|
|
|
|
|
|
2017-04-24 21:04:52 +00:00
|
|
|
|
public int Count {
|
2017-04-21 21:04:03 +00:00
|
|
|
|
get {
|
|
|
|
|
return Clients.Count;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2017-04-24 21:04:52 +00:00
|
|
|
|
public void StopThread() {
|
|
|
|
|
Running = false;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public bool Finished { get; private set; }
|
|
|
|
|
|
2017-04-21 21:04:03 +00:00
|
|
|
|
// USED FOR THREADING -- DO NOT CALL
|
|
|
|
|
public void ManageStack() {
|
2017-04-24 21:04:52 +00:00
|
|
|
|
while(Running && (Count > 0 || RunWithNoClients)) {
|
|
|
|
|
for(var i = Count - 1; i >= 0 && Running; ++i) {
|
2017-04-27 20:44:30 +00:00
|
|
|
|
Clients[i].OnParse();
|
2017-04-24 21:04:52 +00:00
|
|
|
|
|
|
|
|
|
|
|
|
|
|
}
|
|
|
|
|
}
|
2017-04-21 21:04:03 +00:00
|
|
|
|
|
2017-04-24 21:04:52 +00:00
|
|
|
|
Finished = true;
|
|
|
|
|
PoolRef.InvalidateThread(this);
|
2017-04-21 21:04:03 +00:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|