473,725 Members | 2,127 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Thread and GUI update problem

To all,

I have a GUI program (use c#), and I have create a Thread for loading
some bulk data, I also arrange the GUI program like this:

1) load a form showing "Wait for loading..." etc
2) a Thread is then created to load the bulk data
3) after the thread has completed, close the "Wait for loading" form
4) show the main form for the GUI program

The problem is that if I show the "waiting" form, that form's GUI will
not work properly (no repaint event and hangs around, ie. a blank
window), the worse thing is that the Thread may not work properly too
(actually it will stop executing, waiting for locks, maybe ??)

But if I start the Thread without showing any forms; it works
perfectly ????!

What's wrong ?? (the same things happen under .Net Compact Framework)

[code snippet for the main GUI form]
public class Trial04_02 : System.Windows. Forms.Form
{
private System.Windows. Forms.Label label1;
private System.Windows. Forms.Button button1;
private System.Componen tModel.Containe r components = null;
private Trial04_01 mFrmSplash;
private Thread mThr_Main;
private System.Windows. Forms.ListBox listBox1;
private CommonEngine02 mCEng;

public Trial04_02()
{
InitializeCompo nent();
init ();
}

private void InitializeCompo nent() {}

protected void init ()
{
// 1st show splash form
this.mFrmSplash = new Trial04_01 ();
//this.mFrmSplash .Show ();

// 2nd create a thread to load sth...
// CommonEngine02 is a class containing the
// data loading function
this.mCEng = new CommonEngine02 (); this.mThr_Main = new Thread
(new ThreadStart (this.mCEng.thr eadTask));
this.mThr_Main. Start ();
this.mThr_Main. Join ();
this.mFrmSplash .Close ();

// 3rd other setup(s)
// get back the loaded data
System.Collecti ons.ArrayList oArr
= this.mCEng.getA rr_Data ();
for (int i=0; i<oArr.Count; i++)
{
this.listBox1.I tems.Add (oArr[i]);
}
this.Show ();
}

static void Main ()
{
Application.Run (new Trial04_02 ());
}
}
}

[/code]
From Jason (Kusanagihk)
Nov 16 '05
13 3630
Jason Jacob <50******@alumn i.cityu.edu.hk> wrote:
The Main Form's code


That's *still* not a complete example.

However, the problem certainly does seem to be that you're doing all
the actual work before calling Application.Run , so you're not starting
the message pump on the thread until rather late.

Also, although you're *creating* an instance of Form2, you're never
showing it, as far as I can see.

By the way, I'd strongly recommend using MS's naming conventions:
http://tinyurl.com/2cun

You might also want to think about giving your classes more meaningful
names :)

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #11
To Jon

Um... I think I may need a simple guideline to implement Splash
Screen(s). Since my prior trials are on a wrong track, I think it is
difficult to code the right things out........

According to your suggestion, it seems that I may need another program
(maybe a console app) to start 2 threads (1 is for the main form --
loading bulky things etc, the other thread is for the Splash Screen),
then somehow the extra app will control when to kill the Splash Form
and show the main form out.
(Is that correct ???)

Full of question marks.......

From Jason (Kusanagihk)
Nov 16 '05 #12
Jason Jacob <50******@alumn i.cityu.edu.hk> wrote:
Um... I think I may need a simple guideline to implement Splash
Screen(s). Since my prior trials are on a wrong track, I think it is
difficult to code the right things out........

According to your suggestion, it seems that I may need another program
(maybe a console app) to start 2 threads (1 is for the main form --
loading bulky things etc, the other thread is for the Splash Screen),
then somehow the extra app will control when to kill the Splash Form
and show the main form out.
(Is that correct ???)


No, you don't need another program at all. You need to have one thread
which is just running the UI, via Application.Run . It shows the splash
screen, and starts another thread. When the other thread has finished
what it needs to do, it signals that to the UI thread, which puts up
the real UI instead.

One tricky thing here is that you may need to use the version of
Application.Run which *doesn't* take a Form, as otherwise when that
Form is closed, you'll end up losing the message pump.

Alternatively, you could call Application.Run on the splash screen, and
then Application.Run on the main UI.

Alternatively (again) you could create the main UI form and have it as
non-visible, create the splash screen as visible, and call
Application.Run on the main UI form.

Here's a version which uses the middle idea:

using System;
using System.Windows. Forms;
using System.Drawing;
using System.Threadin g;

using Timer = System.Windows. Forms.Timer;

delegate void LoadFinishedHan dler();

class Test
{

static void Main()
{
Loader loader = new Loader();
SplashScreen splash = new SplashScreen(lo ader);
Application.Run (splash);
Application.Run (new MainForm());
}
}

class SplashScreen : Form
{
ProgressBar progress;
Timer timer;

public SplashScreen (Loader loader)
{
loader.LoadFini shed += new LoadFinishedHan dler(LoadFinish ed);
ControlBox = false;
Size = new Size(200, 80);
StartPosition = FormStartPositi on.CenterScreen ;

Label lbl = new Label();
lbl.Text = "Please wait";
lbl.Size = new Size (100, 20);
lbl.Location = new Point (10, 20);
Controls.Add(lb l);

progress = new ProgressBar();
progress.Minimu m = 1;
progress.Maximu m = 5;
progress.Step = 1;
progress.Value = 1;
progress.Size = new Size (160, 20);
progress.Locati on = new Point (10, 50);
Controls.Add(pr ogress);

timer = new Timer();
timer.Interval = 500;
timer.Tick += new EventHandler (TimerTick);
timer.Enabled = true;

loader.Start();
}

void TimerTick(objec t sender, EventArgs e)
{
if (progress.Value == progress.Maximu m)
{
progress.Value = progress.Minimu m;
}
else
{
progress.Perfor mStep();
}
}

protected override void Dispose(bool disposing)
{
base.Dispose(di sposing);
timer.Dispose() ;
}

void LoadFinished()
{
if (InvokeRequired )
{
Invoke(new LoadFinishedHan dler(LoadFinish ed));
return;
}
Close();
}
}

class MainForm : Form
{
public MainForm()
{
Size = new Size(300, 300);
StartPosition = FormStartPositi on.CenterScreen ;

Label lbl = new Label();
lbl.Text = "Main UI goes here";
lbl.Size = new Size (100, 20);
lbl.Location = new Point (10, 20);
Controls.Add(lb l);
}
}

class Loader
{
object stateLock = new object();
LoadFinishedHan dler loadFinishedDel egate;

public event LoadFinishedHan dler LoadFinished
{
add
{
lock (stateLock)
{
loadFinishedDel egate += value;
}
}
remove
{
lock (stateLock)
{
loadFinishedDel egate -= value;
}
}
}

protected virtual void OnLoadFinished( )
{
LoadFinishedHan dler handler;
lock (stateLock)
{
handler = loadFinishedDel egate;
}
if (handler != null)
{
handler();
}
}

public void Start()
{
new Thread (new ThreadStart(Loa d)).Start();
}

void Load()
{
// Obviously you'd do real stuff here
Thread.Sleep(50 00);
OnLoadFinished( );
}
}

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #13
To Jon

Thanks for your advice, I am now your code example to implement the
splash screen and it work fine!

This problem really has taken me too much time.......

Thanks!

From Jason (Kusanagihk)
Nov 16 '05 #14

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

Similar topics

44
2367
by: Charles Law | last post by:
Hi guys. I'm back on the threading gig again. It's the age-old question about waiting for something to happen without wasting time doing it. Take two threads: the main thread and a worker thread. The worker thread is reading the serial port, waiting for something to happen (a service request). When it does it raises an event. Of course, the event is executed on the worker thread. The idea is that when the event is raised, the handler...
12
1549
by: serge calderara | last post by:
Dear all, I have a function that I need to run in a thread due to the fact that it can takes long time to execute according to the amount of data to collect. This function is also populating a treeview control whne collected data gets finished. In order to achieve this I have used the following code : System.Threading.ThreadPool.QueueUserWorkItem(New System.Threading.WaitCallback(AddressOf GetListOfReelsFromRemoteDB))
2
11787
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.
2
1745
by: Don Tucker | last post by:
Hello, I am using Visual Studio 2005 .Net, coding in C#. I am working through the threading walkthrough: ms-help://MS.VSCC.v80/MS.MSDNQTR.v80.en/MS.MSDN.v80/MS.VisualStudio.v80.en/dv_fxmclicc/html/7bc03b7b-d680-499b-8179-5f414b2d650c.htm and have been able to get that to work as designed. However, I coded up a slight variant of that example to update the GUI while each thread is running rather than only at the end of each thread. My...
9
5834
by: Jervin Justin | last post by:
Hi, I've been having this problem for some time with Web Forms: I have a web app that sends data to a service when the user presses a button. Based on the data, the server will send several replies. Since there is no way for a service to post to a client, I am using a thread on the client that polls the server for updates. (Feel free to recommend changes to that as well)
4
3583
by: Charles Law | last post by:
Hi guys. I have two threads: a main thread and a background thread. Lots of stuff happens in the background thread that means I have to update several (lots) of controls on a form. It is quite tiresome to have to write code to call MyControl.Invoke for each control on the form, along with the delegates that are required for each. Is there a better way to do this? What I mean is, if I could marshal the
14
6888
by: joey.powell | last post by:
I am using VS2005 for a windows forms application. I need to be able to use a worker thread function to offload some processing from the UI thread. The worker thread will need access to a datagridview on the form. I am using the following code to spawn the worker thread... Thread WorkerThread = new Thread(new ThreadStart(WT_MyFunction)); WorkerThread.IsBackground = true; WorkerThread.Start(); The problem I am having is...I cannot seem...
8
5367
by: =?Utf-8?B?R3JlZyBMYXJzZW4=?= | last post by:
I'm trying to figure out how to modify a panel (panel1) from a backgroundworker thread. But can't get the panel to show the new controls added by the backgroundwork task. Here is my code. In this code there is a panel panel1, that I populate with a lable in the foreground. Then when I click on "button1" a backgroundworker thread in async mode is started. When the backgoundworker thread completes the thread returns a panel to populate...
20
5533
by: cty0000 | last post by:
I have some question.. This is my first time to use thread.. Following code does not have error but two warring The warring is Warning 2 'System.Threading.Thread.Suspend()' is obsolete: 'Thread.Suspend has been deprecated. Please use other classes in System.Threading, such as Monitor, Mutex, Event, and Semaphore, to synchronize Threads or protect resources. http://go.microsoft.com/fwlink/?linkid=14202'
5
1791
by: P.J.M. Beker | last post by:
Hi there, I'm currently writing a program in which I use the FileMonitor to monitor a folder in which I store downloaded images. I know that I can't add much coding in the filemonitor's event in risk of losing some new entries, so I've deceided to create an update thread. This thread is created when the program's start and should (for various reason) run not in sync with the Filemonitor. The Filemonitor event creates an entry in a...
0
8888
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8752
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9401
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. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9257
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 captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9113
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 choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8097
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 launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6702
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4784
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3221
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

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.