-
Notifications
You must be signed in to change notification settings - Fork 14
Open
Description
Thanks for the code. It got me up and running very quickly and now i have a functioning basic irc twitch chat thing. So here's a fix i wanted to share:
This will stop the threads from pounding the CPU into oblivion (like i said in the title, this will lower the cpu usage from like 25% to 0%). Their is also Thread.Yield() but Thread.Sleep(1) works better i think.
private void IRCInputProcedure(System.IO.TextReader input, System.Net.Sockets.NetworkStream networkStream)
{
while (!stopThreads)
{
if (!networkStream.DataAvailable)
{
Thread.Sleep(1); // Small delay.
continue;
}
...
Thread.Sleep(1); // Small delay.
}
}
private void IRCOutputProcedure(System.IO.TextWriter output)
{
while (!stopThreads)
{
...
Thread.Sleep(1); // Small delay.
}
}
One step better is, "private bool stopThreads = false;", (which should be a "volatile bool") works but this would be better i think:
void IRC_XXX_Procedure(...)
{
do {
/* Work */
} while (_stopWorkerThreadEvent.WaitOne(1) == NONSIGNALED); // Test if event-wait-handle is signaled. WaitOne(1) is equivalent to Thread.Sleep(1).
}
void StopThreads()
{
... i'm paraphrasing here just to demonstrate ManualResetEvent.
stopThreads.Set(); // Tell the threaded functions to stop looping.
... try to wake up the threads if sleeping.
... try to join the threads to see if they are terminated and abort if they won't stop after a delay.
stopThreads.Reset(); // Allow threaded functions to loop the next time it gets started.
}
private ManualResetEvent stopThreads = new ManualResetEvent(NONSIGNALED);
private const bool SIGNALED = true;
private const bool NONSIGNALED = false;
Also, when you make the thread objects, set their "IsBackground = true" so they stop when the program exists. At least i think that's what that property provides ;p
outProc = new System.Threading.Thread(() => IRCOutputProcedure(output)) { IsBackground = true };
...
inProc = new System.Threading.Thread(() => IRCInputProcedure(input, networkStream)) { IsBackground = true };
epcau and mdotstrange
Metadata
Metadata
Assignees
Labels
No labels