Thread not updating progress bar control - C#

I have a custom form with a custom progress bar, spawned in the main class(main thread). Then I spawn a thread and send it a ThreadStart function. This thread start function should update the progress bar in the custom control, but doesnt.:

class MyClass
{
......
//Custom form with progress bar
public CustomFormWithProgressBar statusScreen = new CustomFormWithProgressBar(0);
//thread to use
private Thread myThread;

.....
//Linked to a button to trigger the update procedure.
void ButtonPressEvent(.......)
{
    //create a sub thread to run the work and handle the UI updates to the progress bar
    myThread = new Thread(new ThreadStart(ThreadFunction));
    myThread.Start();
}
.....
//The function that gets called when the thread runs
public void ThreadFunction()
{
    //MyThreadClass myThreadClassObject = new MyThreadClass(this);
    //myThreadClassObject.Run();
    statusScreen.ShowStatusScreen();

    for (int i = 0; i < 100; i++ )
    {
        statusScreen .SetProgressPercentage(i);
        Thread.Sleep(20);
    }
    statusScreen.CloseStatusScreen();
}

Now my statusScreen form just sits and does nothing. No updates occur. But i have confirmed that the sub thread is indeed created and while i am in ThreadFunction, i am runnin on the new thread. Determined this through the Thread window in visual studio.

Why are my updates to the progress percentage of the status screen not being shown? How can i get my updates to push new values to the progress screen and have it show live?

Please note that the integer values being send into the status screen functions represent a percentage of completion. The Thread.Sleep is simply to see the updates if/when the happen.

Note this is not a re-drawing issue. i call Invalidate when the progress percentage is passed into the custom progress bar

Answers


You can not update Controls from another thread.

The right way - is using BackgroundWorker for your purposes. Another way (almost right way) - use Control.Invoke method. And one more another almost right way - use SynchronizationContext.

But you may choose a dark side of power and use CheckForIllegalCrossThreadCalls - static property of Control class and set it to false.


Need Your Help

Creating dynamic search using T-SQL stored procedures

tsql search stored-procedures dynamic

Is there a way to create search based on number of words?

Relationship not set to null

c# entity-framework null entity-framework-6.1

I have a very simple EF operation that fails: break the relationship between two entities as shown in the code below:

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.