[SOLVED] Custom Chat GUI Freezes After StreamReader Returns Null

I really hope that this question doesn’t get asked too frequently, but I simply cannot find an answer for it. I am using C# and Windows Forms to create a GUI to manage a custom Twitch bot. I am able to connect to the server and I get the whole

:tmi.twitch.tv 001 :Welcome, GLHF!
:tmi.twitch.tv 002 :Your host is tmi.twitch.tv
:tmi.twitch.tv 003 :This server is rather new
:tmi.twitch.tv 004 :-
:tmi.twitch.tv 375 :-
:tmi.twitch.tv 372 :You are in a maze of twisty passages.
:tmi.twitch.tv 376 :>

And then I join my channel. As soon as it returns “End of /names list,” the next stream read returns null and my GUI just stops responding. The craziest thing is that it still works! I can type in chat commands and the bot will respond properly, I just can’t interact with the GUI or even debug it in Visual Studios. I actually have the StreamRead function inside a timer, and it acts like the timer isn’t even ticking anymore. I’ll provide any code necessary, I just can’t figure this out.

I had a similar situation in the past where my reader would just return null/empty strings for seemingly unknown reasons.

As to why your UI freezes, this ismy best guess as to why it’s happening without knowing exactly how you’re handling things. You’re timer is calling your read function very frequently, and not just when your stream peaks. Unless you have safeguard checks against processing null data, it will halt and freeze the thread managing your UI since it’s trying to process null data very rapidly. A quick solution to get around this would be to put in checks if there are none, but a more permanent solution would be to make your read function async so the UI can remain responsive.

Instead of putting the read function in a timer, I’d recommend managing your own thread and using ReadLineAsync. It will require some more leg work but it is well worth it in my opinion. Unlike a timer, you have full control over your thread and instead of polling ever so often to read from the socket, it will only do work when your reader peaks or has data in it’s buffer. If you need an example, here’s how I implemented it in my library. I used a regular socket instead of a reader, but conceptually it’s the same.

Oh yay. I am so bad with multiple threads. I haven’t had a ton of practice with them, so this may take me a while to figure out. Thank you for your response, though. It makes sense as to why this would freeze my application.

Got it! Thank you so much for your help! And thank you for sharing your code. That would’ve taken me ages to figure out on my own.

No problem! Using threads is more intimidating than it sounds. The biggest thing is making sure every resource is thread safe, other than that it’s not that bad.

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.