0

I'm currently trying to create a separate thread that will display a Server Message but I get thrown an error, saying I'm using the wrong thread for label 2.

My code looks like this

Thread MOTD = new Thread(() =>
    {
        System.Net.WebClient wc = new System.Net.WebClient();
        // Use webclient to download webpage from target URL
        byte[] raw = wc.DownloadData("https://targaryentech.com/Backend/test.txt");
        // Convert to string
        string webData = System.Text.Encoding.UTF8.GetString(raw);
        // String to MessageBox
        label2.Text = webData;
     });
MOTD.Start();
tzrm
  • 513
  • 1
  • 8
  • 14
Karky
  • 1
  • 1
  • Label 2 is more than likely on the “main thread” as it’s created and placed there, you should look into invoking a control – traveler3468 Sep 01 '18 at 19:51
  • @Karky - you can check the duplicate question I have listed. It shows you how you can do this. You need to perform the label update in the main thread. You do this by invoking. There are examples in the duplicate, as well as one answer which gives a pretty good explanation of the UI threading model. – pstrjds Sep 01 '18 at 19:56
  • @Karky - On a side note, `WebClient` implements `IDisposable` and so you should be calling [Dispose](https://learn.microsoft.com/en-us/dotnet/api/system.componentmodel.component.dispose?view=netframework-4.7.2#System_ComponentModel_Component_Dispose) on it when you are finished with it. An easy way to do that would be to wrap it in a `using` statement. – pstrjds Sep 01 '18 at 20:06

1 Answers1

-1

Ui labels (which I suppose that label2 is)can only be modified from the main thread.

random
  • 487
  • 1
  • 9
  • 19
  • What I want to do is have the label change text for 2 seconds then disappear, but I don't want to freeze up the main thread, because there's a lot of important stuff on it – Karky Sep 01 '18 at 19:54
  • Ok, I see. Ui controls (like labels) can just be modified from the thread it was created on. – random Sep 01 '18 at 19:56
  • @random - While this, in a sense, answers the question of "Why is this happening?" it doesn't show how to solve the problem. – pstrjds Sep 01 '18 at 20:08
  • @pstrjds do you have any workarounds as to how i should go about doing this? BTW: added Dispose() ty – Karky Sep 01 '18 at 20:14
  • @Karky - There isn't a "workaround" in the pure sense of "workaround" since this is not a bug or shortcoming, it is just the nature of the implementation. The solution is to invoke into the UI thread to update UI controls. I am guessing you are using WinForms so I am giving you docs for that. In WinForms you will notice that your `Label` has a property [InvokeRequired](https://docs.microsoft.com/en-us/dotnet/api/system.windows.forms.control.invokerequired?view=netframework-4.7.2#System_Windows_Forms_Control_InvokeRequired) if this returns `true` then you have to Invoke to update the label. – pstrjds Sep 01 '18 at 21:07