473,569 Members | 2,701 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 BackgroundProce ss.

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(o bject sender, System.EventArg s e)

{

// Create and show the splash screen

SplashScreen frmSS = new SplashScreen();

frmSS.Show();

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

BackgroundProce ss bp = new BackgroundProce ss();

bp.StartingDire ctory = @"C:\";

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

System.Threadin g.Thread activeThread = new System.Threadin g.Thread(new
System.Threadin g.ThreadStart(b p.StartProcess) );

activeThread.St art();

while (activeThread.I sAlive)

{

Application.DoE vents();

}

// 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 11774
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 BackgroundProce ss.

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(o bject sender, System.EventArg s e)

{

// Create and show the splash screen

SplashScreen frmSS = new SplashScreen();

frmSS.Show();

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

BackgroundProce ss bp = new BackgroundProce ss();

bp.StartingDire ctory = @"C:\";

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

System.Threadin g.Thread activeThread = new System.Threadin g.Thread(new
System.Threadin g.ThreadStart(b p.StartProcess) );

activeThread.St art();

while (activeThread.I sAlive)

{

Application.DoE vents();

}

// 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.Collecti ons;
using System.Componen tModel;
using System.Windows. Forms;
using System.Threadin g;

namespace CSharpExample.M yApp
{
/// <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.ProgressB ar progressBar1;

/// <summary>
/// Required designer variable.
/// </summary>
private System.Componen tModel.Containe r components = null;

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

//
// TODO: Add any constructor code after InitializeCompo nent call
//
}

[STAThread]
static void Main()
{
SplashForm splashForm = new SplashForm();
splashForm.Show Dialog();
splashForm.Dial ogResult = DialogResult.OK ;
if ( splashForm.Dial ogResult == DialogResult.Ca ncel )
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.Disp ose();
}
}
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 InitializeCompo nent()
{
this.label1 = new System.Windows. Forms.Label();
this.lblText = new System.Windows. Forms.Label();
this.btnClose = new System.Windows. Forms.Button();
this.progressBa r1 = new System.Windows. Forms.ProgressB ar();
this.SuspendLay out();
//
// label1
//
this.label1.Fon t = new System.Drawing. Font("Microsoft Sans Serif", 9.75F,
System.Drawing. FontStyle.Bold, System.Drawing. GraphicsUnit.Po int,
((System.Byte)( 0)));
this.label1.Loc ation = new System.Drawing. Point(16, 16);
this.label1.Nam e = "label1";
this.label1.Siz e = new System.Drawing. Size(264, 23);
this.label1.Tab Index = 0;
this.label1.Tex t = "Welcome";
//
// lblText
//
this.lblText.Lo cation = new System.Drawing. Point(16, 56);
this.lblText.Na me = "lblText";
this.lblText.Si ze = new System.Drawing. Size(264, 23);
this.lblText.Ta bIndex = 1;
this.lblText.Te xt = "Loading XYZ...";
//
// btnClose
//
this.btnClose.L ocation = new System.Drawing. Point(208, 128);
this.btnClose.N ame = "btnClose";
this.btnClose.T abIndex = 2;
this.btnClose.T ext = "Cancel";
this.btnClose.C lick += new System.EventHan dler(this.btnCl ose_Click);
//
// progressBar1
//
this.progressBa r1.Location = new System.Drawing. Point(16, 96);
this.progressBa r1.Name = "progressBa r1";
this.progressBa r1.Size = new System.Drawing. Size(264, 23);
this.progressBa r1.Step = 1;
this.progressBa r1.TabIndex = 3;
//
// SplashForm
//
this.AutoScaleB aseSize = new System.Drawing. Size(5, 13);
this.ClientSize = new System.Drawing. Size(292, 159);
this.Controls.A dd(this.progres sBar1);
this.Controls.A dd(this.btnClos e);
this.Controls.A dd(this.lblText );
this.Controls.A dd(this.label1) ;
this.FormBorder Style = System.Windows. Forms.FormBorde rStyle.FixedDia log;
this.Name = "SplashForm ";
this.Text = "Loading MyApp...";
this.Load += new System.EventHan dler(this.Spash Form_Load);
this.ResumeLayo ut(false);

}
#endregion

private void SpashForm_Load( object sender, System.EventArg s e)
{
Thread t = new Thread(new ThreadStart(Wor kerStart));
t.IsBackground = true;
t.Start();
}

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

private void Done()
{
if ( InvokeRequired )
{
Invoke(new MethodInvoker(D one));
}
else
{
this.lblText.Te xt = "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.EventArg s e)
{
this.DialogResu lt = DialogResult.Ca ncel;
//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
4898
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 GUI is updating.  I've done that before without a problem, however, now, I need to pass variables to the separate Thread or Runnable that I'm...
5
2185
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 bar. Im having problems as the screen isn't being redrawn properly. If I call DoEvents each time then it works ok. I want to dump DoEvents to prevent...
3
3762
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 have it run in the main thread. I have read many examples and tried numerous approaches based on delegates all of which will launch the method, but...
2
1178
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 named SplashScreen, and a C# class library named BackgroundProcess.
14
2927
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 utilise the disco file to update the Corresponding proxy file and reflect the changes made to the web service. However, the results of doing this with...
5
12502
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 update the datasource - awesome, but I have an issue with updating from a different thread. Here is my datasource, a person class that raises the...
3
7293
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; AppDomain.CurrentDomain.UnhandledException += delegate(object sender, UnhandledExceptionEventArgs e) { exceptionText = e.ExceptionObject.ToString();
2
1308
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 Application.Run, and then I have a secondary window (a welcome screen) which is created afterwards and shown on the same thread. However, the problem is...
8
1980
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, NULL, CRect( 0,0,0,0), pParent, pNode->m_nFinsID) )
0
7924
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
8120
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
0
7968
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6283
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
0
3653
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3640
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2113
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1212
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
937
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

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.