Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

This will drop the cpu usage from 25% to 0% #4

Open
FocusedWolf opened this issue Feb 23, 2019 · 0 comments
Open

This will drop the cpu usage from 25% to 0% #4

FocusedWolf opened this issue Feb 23, 2019 · 0 comments

Comments

@FocusedWolf
Copy link

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 };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant