473,398 Members | 2,335 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,398 software developers and data experts.

Updating the UI from a Secondary Thread

BG
We're having trouble writing the code to update a UI control (label.Text)
from a secondary thread. We're using C# with Windows Forms.

We have a main form named MainForm, a splash screen form named SplashScreen,
and a C# class library named BackgroundProcess.

On application start, we simply want to show the splash screen form, kick
off the background processing on a separate thread, and, at different points
in the background processing, update a label on the splash screen to inform
the user of what the application is doing. When the processing is done, the
splash screen form goes away and the main form appears.

In the main form's form load event we have:

private void MainForm_Load(object sender, System.EventArgs e)

{

// Create and show the splash screen

SplashScreen frmSS = new SplashScreen();

frmSS.Show();

// Create the object for background processing and set an initial
property

BackgroundProcess bp = new BackgroundProcess();

bp.StartingDirectory = @"C:\";

// Create a new thread for the background processing and start it

System.Threading.Thread activeThread = new System.Threading.Thread(new
System.Threading.ThreadStart(bp.StartProcess));

activeThread.Start();

while (activeThread.IsAlive)

{

Application.DoEvents();

}

// Clean up

activeThread = null;

bp = null;

frmSS.Close();

frmSS = null;

}

This code works, and the code in our class library (i.e., the background
processing code) works, but we still can't get the splash screen's label to
update.

We've trying using delegates/events, etc. and have not been successful in
getting the label updated from the secondary thread that's doing all the
"behind-the-scenes" processing.

Any suggestions?

Thanks.


Nov 16 '05 #1
2 11759
I am probably missing something here, but I suspect that the problem is
your background thread is calling a delegate in your splash screen that
attempts to update the label in the same thread as the delegate was
called on.

You cannot (well, I guess technically you can, but it can get ugly)
update any forms elements except on the thread that they were created
on. Instead, in the recipient of the call to update the label (in your
splash screen) check to see if InvokeRequired is true, and then use
invoke on that control to have it execute on the proper thread.

John

BG wrote:
We're having trouble writing the code to update a UI control (label.Text)
from a secondary thread. We're using C# with Windows Forms.

We have a main form named MainForm, a splash screen form named SplashScreen,
and a C# class library named BackgroundProcess.

On application start, we simply want to show the splash screen form, kick
off the background processing on a separate thread, and, at different points
in the background processing, update a label on the splash screen to inform
the user of what the application is doing. When the processing is done, the
splash screen form goes away and the main form appears.

In the main form's form load event we have:

private void MainForm_Load(object sender, System.EventArgs e)

{

// Create and show the splash screen

SplashScreen frmSS = new SplashScreen();

frmSS.Show();

// Create the object for background processing and set an initial
property

BackgroundProcess bp = new BackgroundProcess();

bp.StartingDirectory = @"C:\";

// Create a new thread for the background processing and start it

System.Threading.Thread activeThread = new System.Threading.Thread(new
System.Threading.ThreadStart(bp.StartProcess));

activeThread.Start();

while (activeThread.IsAlive)

{

Application.DoEvents();

}

// Clean up

activeThread = null;

bp = null;

frmSS.Close();

frmSS = null;

}

This code works, and the code in our class library (i.e., the background
processing code) works, but we still can't get the splash screen's label to
update.

We've trying using delegates/events, etc. and have not been successful in
getting the label updated from the secondary thread that's doing all the
"behind-the-scenes" processing.

Any suggestions?

Thanks.

Nov 16 '05 #2
Here is one way that loads the spash form and kicks the worker and waits
till close, then starts the main form using Application.Run(new MyForm());
as normal. The worker calls private methods in the form that make sure the
calls are done on the forms thread. Using this pattern, you can update any
controls on your form.

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Threading;

namespace CSharpExample.MyApp
{
/// <summary>
/// Summary description for SpashForm.
/// </summary>
public class SplashForm : System.Windows.Forms.Form
{
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label lblText;
private System.Windows.Forms.Button btnClose;
private System.Windows.Forms.ProgressBar progressBar1;

/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;

public SplashForm()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();

//
// TODO: Add any constructor code after InitializeComponent call
//
}

[STAThread]
static void Main()
{
SplashForm splashForm = new SplashForm();
splashForm.ShowDialog();
splashForm.DialogResult = DialogResult.OK;
if ( splashForm.DialogResult == DialogResult.Cancel )
return;
Application.Run(new MyForm());
}

/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}

#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.label1 = new System.Windows.Forms.Label();
this.lblText = new System.Windows.Forms.Label();
this.btnClose = new System.Windows.Forms.Button();
this.progressBar1 = new System.Windows.Forms.ProgressBar();
this.SuspendLayout();
//
// label1
//
this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F,
System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point,
((System.Byte)(0)));
this.label1.Location = new System.Drawing.Point(16, 16);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(264, 23);
this.label1.TabIndex = 0;
this.label1.Text = "Welcome";
//
// lblText
//
this.lblText.Location = new System.Drawing.Point(16, 56);
this.lblText.Name = "lblText";
this.lblText.Size = new System.Drawing.Size(264, 23);
this.lblText.TabIndex = 1;
this.lblText.Text = "Loading XYZ...";
//
// btnClose
//
this.btnClose.Location = new System.Drawing.Point(208, 128);
this.btnClose.Name = "btnClose";
this.btnClose.TabIndex = 2;
this.btnClose.Text = "Cancel";
this.btnClose.Click += new System.EventHandler(this.btnClose_Click);
//
// progressBar1
//
this.progressBar1.Location = new System.Drawing.Point(16, 96);
this.progressBar1.Name = "progressBar1";
this.progressBar1.Size = new System.Drawing.Size(264, 23);
this.progressBar1.Step = 1;
this.progressBar1.TabIndex = 3;
//
// SplashForm
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(292, 159);
this.Controls.Add(this.progressBar1);
this.Controls.Add(this.btnClose);
this.Controls.Add(this.lblText);
this.Controls.Add(this.label1);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.Name = "SplashForm";
this.Text = "Loading MyApp...";
this.Load += new System.EventHandler(this.SpashForm_Load);
this.ResumeLayout(false);

}
#endregion

private void SpashForm_Load(object sender, System.EventArgs e)
{
Thread t = new Thread(new ThreadStart(WorkerStart));
t.IsBackground = true;
t.Start();
}

private delegate void UpdatePBarDelegate(int step);
private void UpdatePBar(int step)
{
if ( InvokeRequired )
{
UpdatePBarDelegate ud = new UpdatePBarDelegate(UpdatePBar);
Invoke(ud, new object[]{step});
}
else
{
this.progressBar1.Value = this.progressBar1.Value + step;
}
}

private void Done()
{
if ( InvokeRequired )
{
Invoke(new MethodInvoker(Done));
}
else
{
this.lblText.Text = "Done";
this.Close();
}
}

private void WorkerStart()
{
for(int i = 0; i < 100; i++)
{
this.UpdatePBar(1); // Update progress bar 1 step.
Thread.Sleep(50); // Fake some delay - your processing goes here.
}
this.Done(); // Do any other updates on the splash form and load main and
quit.
}

private void btnClose_Click(object sender, System.EventArgs e)
{
this.DialogResult = DialogResult.Cancel;
//this.Close();
}
}
}

--
William Stacey
MVP Directory Services
http://mvp.support.microsoft.com
Nov 16 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: Hal Vaughan | last post by:
First, I am aware of both SwingUtilities.invokeLater(), and of using Thread to create a new thread.  These are part of the problem. I want to have something running in the background, while the...
5
by: Claire | last post by:
My progress window is created by a secondary thread and then updated by it while a file is uploaded. There's an avi animation control on there that should show the move file avi. Plus a progress...
3
by: Dale Lundgren | last post by:
I have a c# class library that launches a Win Form in a secondary thread. From the Form (now running in the secondary thread) I need to be able to start a method that is defined in the class and...
2
by: BG | last post by:
We're having trouble writing the code to update a UI control (label.Text) from a secondary thread. We're using C# with Windows Forms. We have a main form named MainForm, a splash screen form...
14
by: el_sid | last post by:
Our developers have experienced a problem with updating Web References in Visual Studio.NET 2003. Normally, when a web service class (.asmx) is created, updating the Web Reference will...
5
by: Mark R. Dawson | last post by:
Hi all, I may be missing something with how databinding works but I have bound a datasource to a control and everything is great, the control updates to reflect the state of my datasource when I...
3
by: Mike Binks | last post by:
I wish to make sure all unhandled exceptions (UE) are handled by a central handler. For primary thread UEs, this may be done by string exceptionText; ...
2
Logan1337
by: Logan1337 | last post by:
Hi. This is an odd question because I'm not sure if it's a bug or if this is how it is supposed to behave, however what is happening is I have a main window of my application that is passed to...
8
by: Daniele Piccinini | last post by:
Hi all, In my vc++ 2005 dialog based application i need to use a comunication activex component in a secondary thread: CFINSAxEFS* pNewAx = new CFINSAxEFS(); if ( !pNewAx->Create( NULL,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.