Threading Problems

I'm using winforms, so to explain my problem as simple as i can.
The problem is that I'm starting a background thread and in that thread im calling a method in the main thread that should change some text in a label, but the thread is closing properly and don't give any errors, but it does not change to text in the label.
The idea is that i want to change the label text from the background thread i have started but since nothing happens i have hit a dead end on how to do this.
I really hope that someone can help me with finding a solution to the problem quickly since this program I'm trying make is a exam assignment that i have to be done with within the next 10 days.

Here is the code i have made:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using System.Net.Sockets;
using System.Net;
using System.Threading;
using System.Diagnostics;
using System.Globalization;

namespace Server
{
    public partial class Server : Form
    {
        public static string ClientAddr;
        public static int PortNum;

        public Server()
        {
            InitializeComponent();
        }

        // This method adds a new line to the status text makes sure that the status text dont get over 12 lines.
        public void AddStatusText(string newLine)
        {
            
            string Text = StatusText.Text;
            Text += "\n" + newLine;
            string[] lines = Regex.Split(Text, "\n");
            string ReturnText = "";

            if (lines.Length <= 12)
            {
                for (int i = 0; i < lines.Length; i++)
                {
                    if (i == 0)
                        ReturnText = lines[i];
                    else
                        ReturnText += "\n" + lines[i];
                }
            }
            else
            {
                int lineNumbers = lines.Length;
                int newStartLine = lineNumbers - 12;

                for (int i = newStartLine; i < lines.Length; i++)
                {
                    if (i == newStartLine)
                        ReturnText = lines[i];
                    else
                        ReturnText += "\n" + lines[i];
                }
            }

            StatusText.Text = ReturnText;
        }

        //This method calls the AddStatusText method, the reason is made like this is so that i can be called from another class.
        public static void CallAddStatusText(string line)
        {
            Server temp = new Server();
            temp.AddStatusText(line);
        }

        // This method makes sure that its a valid ip adresse that have been entered
        public static bool IpCheck(string IpAddr)
        {
            try
            {
                System.Net.IPAddress ipAddress = System.Net.IPAddress.Parse(IpAddr);
                return true;
            }
            catch
            {
                return false;
            }
        }

        // This method makes sure that the entered port is a valid port - There may need to made more to this method.
        public static bool PortCheck(string Port)
        {
            try
            {
                int PortNum = Convert.ToInt32(Port);
                if (PortNum >= 0 && PortNum <= 65535)
                    return true;
                else
                    return false;
            }
            catch
            {
                return false;
            }
        }

        // This is the Start Server button it starts the hole server process
        private void RunServer_Click(object sender, EventArgs e)
        {
            if (!IpCheck(IpAdd.Text))
                MessageBox.Show("The IP adresse is invalid", "ERROR");
            else if (!PortCheck(Port.Text))
                MessageBox.Show("The port number is invalid", "ERROR");
            else
            {
                IpAdd.ReadOnly = true;
                Port.ReadOnly = true;
                RunServer.Enabled = false;
                //ClientAddr = IpAdd.Text;
                PortNum = Convert.ToInt32(Port.Text);
                AddStatusText("The server is starting up.");
                
                //From this point on im testing some treading stuff.
                NetworkHandler networkHandler = new NetworkHandler();
                Thread NetworkHandlerThread = new Thread(new ThreadStart(networkHandler.Handler));
                NetworkHandlerThread.Name = "BackgroundNetworkHandler";
                NetworkHandlerThread.IsBackground = true;
                //NetworkHandlerThread.
                NetworkHandlerThread.Start();

                if (NetworkHandlerThread.IsAlive)
                {
                    AddStatusText("The tread is alive.");
                }
                else
                {
                    AddStatusText("The tread is dead.");
                }   
            }
        }
    }

    class NetworkHandler
    {
        public string IpAdd = Server.ClientAddr;
        public int PortNum = Server.PortNum;
        // This method is handling the network communication
        public void Handler()
        {
            Server.CallAddStatusText("It got this far.....");
        }

        public string ChangeData(string dataString)
        {
            return dataString;
        }
    }
}

Comments

  • You cannot modify GUI object from another thread. You must invoke the change on the Form main thread.
    Use this code:
    string newText = "abc"; // running on worker thread
    someLabel.Invoke((MethodInvoker)delegate {
        someLabel.Text = newText; // runs on UI thread
    });
    

    someLabel is a generic GUI Object.
  • after trying multiple things and ended up with destroying Visual Studio i have decided to not make my program with threading. So i do not need any help with this at the moment, but i may try doing something like this again at some other time, but for now i have to little experience with C# so it will take to long time for me to find and implement a working solution, so i have decided to go back to my first idea.

    Thanks for the help mykhayl, i found it quite useful but i could not really find out how to get it to work tho sadly :(
  • Without having background threads on your UI, when you do any type of long running task your UI will look like it has hung. I would strongly recommend trying to get what mykhayl suggested to work. If you can't get it working, post back with code and the errors you are getting.
Sign In or Register to comment.