2

I have a C# Windows app and there is a Button on Form1 that when pressed runs a long program. While the program is running I want the User Interface to be available so I will put most of the code into a separate thread. As a test, I put code into a thread and looked to see if it would have any problems. I have 2 problems. My ultimate desire is to get the UI to work so let me know if this is not the best way to start a new thread.

First, although the program compiled, the thread that I created does not see ALL of the values in the variables from the main thread. Most of the strings are empty and the int and float values are 0. The only variables that keep their values in the thread are those that are created with a value and then never changed. Obviously, I should be able to see all of the values in all of the variables.

Second, I have a Textbox on the form that I append text to so that I can give information on the long running program. The Textbox displays information from the main thread without a problem but nothing is displayed from the thread that I created. I want the textbox on Form1 to be updated from the thread also.

I am using Visual Studio 2008 on Windows XP.

These are the definitions of the variables. They are in the Program.cs portion of the app.

partial class Form1
{
    string    TBI_File = "";
    int   junk = 27;

    string junkstr = "Two out of three ain\'t bad";
    double RADD;
    string PROGRAMMER = "Don and Jim"; 
    float  currentSize = 8.25F;        
    float sizechange = 10.0F;  
}

In the main thread (after the Button is pressed) I create the new thread. I copied and modified this code from http://msdn.microsoft.com/en-us/library/aa645740(v=vs.71).aspx I commented the Abort and Join because at this point of the testing I want the thread tro continue to run until I stop it separately.

     Wprintf("Alpha.Beta starting");
     Alpha oAlpha = new Alpha();

     // Create the thread object, passing in the Alpha.Beta method
     // via a ThreadStart delegate. This does not start the thread.
     Thread oThread = new Thread(new ThreadStart(oAlpha.Beta));

     // Start the thread
     oThread.Start();

     // Spin for a while waiting for the started thread to become
     // alive:
     while (!oThread.IsAlive) ;

     // Put the Main thread to sleep for 1 millisecond to allow oThread
     // to do some work:
     //original
    //Thread.Sleep(1);
     Thread.Sleep(10);

     // Request that oThread be stopped
     //oThread.Abort();

   // Wait until oThread finishes. Join also has overloads
     // that take a millisecond interval or a TimeSpan object.
     //oThread.Join();

     Wprintf("Alpha.Beta has finished");

Below is the code that is run by the thread.

public class Alpha : Form1
{

    // This method that will be called when the thread is started
    public void Beta()
    {
        while (true)
        {
            //Console.WriteLine("Alpha.Beta is running in its own thread.");
            Wprintf("Alpha.Beta is running in its own thread. " + 
                " RADD: " + RADD + 
                " CurrentSize: " + currentSize.ToString() +
                " TBI_File: " + TBI_File +
                " PROGRAMMER: " + PROGRAMMER +
                " sizechange: " + sizechange.ToString() +
                " junk: " + junk +
                " junkstr: " + junkstr);

           textBox1.AppendText("Alpha.Beta is running in its own thread.");

        }
    }
};

Wprintf appends that message to a log file and adds the messges to the Textbox. It works for the entire program except that appending to the end of the textbox does not work from the thread created. I added the TextBox1.AppendText above (which is in the thread) to try to get that to work but it does not do anything and no message is displayedin the textbox from the thread.

The portion of the log file is below. The log file is appended from the thread so I can see what the values of the variables are in the thread(I also looked at the variables from the debugger and got the same values) Variables changed are RADD and TBI_FILE and you can see below that RADD is 0.0 and TBI_File is ‘’ in the thread. The others are not changed in the program and just got the value that was set when it was declared.

 Alpha.Beta is running in its own thread. RADD: 0  CurrentSize: 8.25 TBI_File:  PROGRAMMER: Don and Jim   sizechange: 10 junk: 27   junkstr: Two out of three ain't bad

I asked about an earlier version of this question here: Initial Form of C# program unavailable while the program is running

As I indicated previously, I need to have the UI (Textbox and clicking the X for exit) to be available so let me know if this is not a good way to do it.

Thanks,

3 Answers 3

5

Several things you want to think about.

Most importantly, you can't modify the UI from the background thread. Only the UI thread can modify the controls. So your textBox1.AppendText won't work. You need to call Invoke to synchronize with the UI thread, like this:

this.Invoke((MethodInvoker) delegate
    {
        textBox1.Append("Alpha.Beta is running in its own thread.");
    });

Of course, that's not going to update the UI because your UI thread is waiting for the background thread to complete.

You can struggle with managing your own threads, but you're better off using the BackgroundWorker, which handles most of the nasty details for you.

// set up the worker
BackgroundWorker worker = new BackgroundWorker();
worker.ReportsProgress = true;
worker.DoWork = worker_DoWork;  // method that's called when the worker starts

// method called to report progress
worker.ProgressChanged = worker_progressChanged;

// method called when the worker is done
worker.RunWorkerCompleted = worker_workCompleted;

// start worker
worker.RunWorkerAsync();


void worker_DoWork(object sender, DoWorkEventArgs e)
{
        //Console.WriteLine("Alpha.Beta is running in its own thread.");
        Wprintf("Alpha.Beta is running in its own thread. " + 
            " RADD: " + RADD + 
            " CurrentSize: " + currentSize.ToString() +
            " TBI_File: " + TBI_File +
            " PROGRAMMER: " + PROGRAMMER +
            " sizechange: " + sizechange.ToString() +
            " junk: " + junk +
            " junkstr: " + junkstr);
    worker.ReportProgress(0, "Alpha.Beta is running in its own thread.");
}

void worker_progressChanged(object sender, ProgressChangedEventArgs e)
{
    textBox1.Append((string)e.UserState);
}

void worker_workCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    textBox1.Append("Worker done!");
}

Your UI thread starts the worker and then just continues. Don't make it wait for the worker to complete. If you want to be notified when the worker is done, you can handle the RunWorkerCompleted event. Or, if you just want to poll to see if the worker is done, you can have a timer periodically check the IsBusy property. You're better off with the RunWorkerCompleted, though.

Don't ever make your UI thread wait for a background thread to complete. If you do, what's the point of having a background thread?

4
  • I had looked at that previously but I did not use it because it did not say anything about Windows XP but I just tried to see if my program compiles with that and it did.... Of course compiling and running are different. Will that allow me to get the values of the variables and change the UI for the initial form? Thanks,
    – Jim
    Jul 23, 2013 at 19:53
  • 1
    @Jim: I don't know what your specific needs are for the initial form or whatever. The code running in the BackgroundWorker has full access to the Form's variables. Just make sure that any changes you make to controls are done either in the progress changed handler, or by calling Invoke to synchronize with the UI thread. Jul 23, 2013 at 20:05
  • @Jim: It was great! Give it a try. Jul 23, 2013 at 21:30
  • I will... Thanks for the info about BackgroundWorker!
    – Jim
    Jul 24, 2013 at 15:34
2

You set the values in an instance of Form. You then create an instance of Alpha which inherits from Form and thus also performs the initializations Form does. Other changes made in Form will not be shown in other instances (excluding static variables). You should either update the Alpha instance or use the same instance.

You cannot access controls from any thread besides the main one. The proper way to do it is use Control.Invoke, see Thread Control.Invoke for example

Also, waiting the way you do (by a while) will get the main thread stuck. If you wish to wait for something to finish - you'll have to work with events (have the worker thread signal it has finished or you a backgroundworker and register for work_completed event).

Something else - Are you sure you wish to inherit from Form? Is this really necessary?

0
1

First of all, let me give you some personal advices for this kind of situation: 1) At this scenario I'd rather use BackgroundWorker instead of a raw Thread class. 2) Threads (no matter what kind of class) cannot communicate with the UI or another thread directly, or at least they shouldn't.

--Let's roll to the answer: Since Threads cannot/should'nt access your main thread variables directly, you'd have to pass them as a parameter to the BackgroundWorker.

Below is a self-explanatory code, please comment below if you still have any question.

    private BackgroundWorker worker = new BackgroundWorker();
    public Form1()
    {
        InitializeComponent();

        //Register the event/handlers for: Do Work, ProgressChanged, and Worker Completed.
        worker.DoWork += new DoWorkEventHandler(worker_DoWork); 
        worker.WorkerReportsProgress = true; //Let's tell the worker that it WILL be ABLE to report progress.
        worker.ProgressChanged += new ProgressChangedEventHandler(worker_ProgressChanged); //Method that will be called when the progress has been changed.            
        worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted); //Method that will be called when the thread finish executing.

        //Start the thread async.
        worker.RunWorkerAsync();
    }

    /// <summary>
    /// Method that will run in a new thread async from the main thread.
    /// </summary>        
    /// <param name="e">Arguments that are passed to the Worker Thread (a file, path, or whatever)</param>
    private void worker_DoWork(object sender, DoWorkEventArgs e)
    {
        //Get the argument. In this example I'm passing a pathFile.
        string pathFile = (string)e.Argument;

        for (int i = 0; i <= 100; i+=10) //For demonstration purposes we're running from 0 to 99;
        {
            System.Threading.Thread.Sleep(100); //Sleep for demonstration purposes.

            //I want to update the Log, so the user will be notified everytime
            //the log is updated through the ReportProgress event.
            string myLog = i + " ";

            //Invoke the event to report progress, passing as parameter the
            //percentage (i) and the current log the thread has modified.
            worker.ReportProgress(i, myLog);
        }            

        e.Result = "I've made it!!!!! - My complex cientific calculation from NASA is 654.123.Kamehameha)";
    }        

    /// <summary>
    /// Invoked when the worker calls the ReportProgress method.
    /// </summary>        
    /// <param name="e">The arguments that were passed throgh the ReportProgress method</param>
    private void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
        //Get the Percentage and update the progressbar.
        progressBar1.Value = e.ProgressPercentage;

        //Get the EventArgs and respectively the new log that the thread has modified and append it to the textbox.
        textBox1.AppendText((string)e.UserState);
    }

    private void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        //Lets check whether the worker has runned successfully (without cancelling and without any errors)
        if (!e.Cancelled && e.Error == null)
        {
            //Lets display the result (Result is an object, so it can return an entire class or any type of data)
            MessageBox.Show((string)e.Result);
        }
    }
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.