Search code examples
c#visual-studio-2015streamreaderirc

Having a StreamReader running makes the application unresponsive


I have a bot which connects to an IRC channel and reads the chat with a StreamReader. Everything works fine, the bot can read and response, but the problem is the Windows Form is freezing while the StreamReader is active.

while(true)
{
    string message = irc.readMessage();
    if (message.Contains("!test"))
    {
        irc.sentChatMessage("answer");
    }
}

I tried putting it on a timer instead of the while loop that ticks every 100ms with no change.

the method

public string readMessage()
    {
        string message = inputStream.ReadLine();
        return message;
    }

Solution

  • This is because inputStream.ReadLine(); is blocking the UI Thread. If you use the async overload StreamReader.ReadLineAsync this will run asynchronously and therefore not block the UI thread.

    Sample:

    async void StartBot()
    {
      while(true)
      {
        string message = await irc.readMessageAsync();
        if (message.Contains("!test"))
        {
            irc.sentChatMessage("answer");
        }
      }
    }
    
    public async Task<string> readMessageAsync()
    {
       string message = await inputStream.ReadLineAsync();
       return message;
    }
    

    You can find more information aswell as samples about async and await here.