November 26

Issues With Threading a Design

This morning I decided that I had done enough research into TwitchLib and that it was time to have something visibly there in the project rather then a blank screen. Finally I had opened Visual Studio and started a new Windows Forms Project and after 10 minutes or so I have a (very rough) design cobbled together that can be seen below.

As you can tell from the image, we have a main central box which will hold all of the Twitch communication in it, with an input box below. On the right, there is an area for a viewer list and an event list which will be updated by the API. By events, we mean; hosts, follows, subscriptions, raids etc.

After throwing this together, I decided to start with a little bit of basic code, so loading the libraries, connecting to Twitch and joining the correct chat room. I then did what any good developer does and added in some rudimentary output to make sure it is all working and that is where I started to run into problems… If I used client.SendMessage() then everything was fine, but if I wrote to the RichTextBox which is meant to be the chat window I had gotten the following error which confused me massively:

After a bit of intense Google Fu (bearing in mind it was 3am at this point!) I managed to stumble across a really good Stack Overflow post that gave me an overview of what was wrong and how to fix it which was excellent. Simply put, the TwitchLib calls were working in a different process to the Windows Forms so it is a security/crashproofing error. The simple work around is to make a callback and work with Invoke() so the WriteText() function has gone from:

public void WriteChat(string text)
{
    chat.Text = chat.Text + "\n" + text;
}

to

delegate void SetTextCallback(string text);

public void WriteChat(string text)
{
if(InvokeRequired)
{
this.Invoke((MethodInvoker)delegate () { WriteChat(text); });
return;
}

chat.Text = chat.Text + "\n" + text;
}

From there, the error has gone and we had the output that we wanted which is awesome! So a bit of safe writing to Win Forms/multi-threading saved the day and worked out to be a helpful tip for the future!

 


Tags: , ,
Copyright 2018. All rights reserved.

Posted November 26, 2018 by marctowler in category "Development", "Updates

Leave a Reply

Your email address will not be published. Required fields are marked *