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

Home Posts Topics Members FAQ

thread synchronization and GUI problem

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.ht m

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 experience is that the GUI is
locked up while each thread is running, though. I have a simple Windows App
form with 2 buttons, 2 text boxes, and 2 labels, and then a class called
Loopy (analogous to the walkthrough Calculator class) [attached below]. My
intention is to loop from 1 to N, where N in a number entered in a text box,
and then display the value of the loop variable on the GUI by updating a
label. Each button-textbox-label combo performs a different loop in a
separate thread. Is there a glaring error in the code or do I just have a
conceptual misunderstandin g?

Thanks,
Don
namespace ThreadEventTest
{
public partial class Form1 : Form
{
Loopy Loopy1;
public delegate void LoopWHandler(in t current);
public delegate void LoopCHandler();

public Form1()
{
InitializeCompo nent();
Loopy1 = new Loopy();
Loopy1.Loop1Wor king += new
Loopy.Loop1Work ingHandler(this .Loop1WHandler) ;
Loopy1.Loop2Wor king += new
Loopy.Loop2Work ingHandler(this .Loop2WHandler) ;
Loopy1.Loop1Com plete += new
Loopy.Loop1Comp leteHandler(thi s.Loop1CHandler );
Loopy1.Loop2Com plete += new
Loopy.Loop2Comp leteHandler(thi s.Loop2CHandler );
}

private void button1_Click(o bject sender, EventArgs e)
{
Loopy1.var1 = int.Parse(textB ox1.Text);
// Disables the btnFactorial1 until this calculation is complete.
button1.Enabled = false;
Loopy1.ChooseTh reads(1);
}

private void button2_Click(o bject sender, EventArgs e)
{
Loopy1.var2 = int.Parse(textB ox2.Text);
// Disables the btnFactorial1 until this calculation is complete.
button2.Enabled = false;
Loopy1.ChooseTh reads(2);
}

protected void Loop1WHandler(i nt current)
// Displays the returned value in the appropriate label.
{
this.BeginInvok e(new LoopWHandler(L1 WHandler), new Object[] {
current });
}

protected void Loop2WHandler(i nt current)
{
this.BeginInvok e(new LoopWHandler(L2 WHandler), new Object[] {
current });
}

protected void Loop1CHandler()
// Displays the returned value in the appropriate label.
{
this.BeginInvok e(new LoopCHandler(L1 CHandler), new Object[] {});
}

protected void Loop2CHandler()
{
this.BeginInvok e(new LoopCHandler(L2 CHandler), new Object[] {});
}

public void L1WHandler(int current)
{
label1.Text = current.ToStrin g();
}
public void L2WHandler(int current)
{
label2.Text = current.ToStrin g();
}
public void L1CHandler()
{
button1.Enabled = true;
}
public void L2CHandler()
{
button2.Enabled = true;
}
}
}

namespace ThreadEventTest
{
public partial class Loopy : Component
{
public int var1;
public int current1;
public int var2;
public int current2;

public delegate void Loop1WorkingHan dler(int current);
public delegate void Loop2WorkingHan dler(int current);
public delegate void Loop1CompleteHa ndler();
public delegate void Loop2CompleteHa ndler();

public event Loop1WorkingHan dler Loop1Working;
public event Loop2WorkingHan dler Loop2Working;
public event Loop1CompleteHa ndler Loop1Complete;
public event Loop2CompleteHa ndler Loop2Complete;

public System.Threadin g.Thread Loop1Thread;
public System.Threadin g.Thread Loop2Thread;

public void Loop1()
{
for (int i = 1; i <= var1; i++)
{
lock (this)
{
current1 = i;
}
Loop1Working(cu rrent1);
}
Loop1Complete() ;
}

public void Loop2()
{
for (int i = 1; i <= var2; i++)
{
lock (this)
{
current2 = i;
}
Loop2Working(cu rrent2);
}
Loop2Complete() ;
}

public void ChooseThreads(i nt threadNumber)
{
// Determines which thread to start based on the value it
receives.
switch (threadNumber)
{
case 1:
// Sets the thread using the AddressOf the subroutine
where
// the thread will start.
Loop1Thread = new System.Threadin g.Thread(new
System.Threadin g.ThreadStart(t his.Loop1));
// Starts the thread.
Loop1Thread.Sta rt();
break;
case 2:
Loop2Thread = new
System.Threadin g.Thread(new
System.Threadin g.ThreadStart(t his.Loop2));
Loop2Thread.Sta rt();
break;
}
}

public Loopy()
{
InitializeCompo nent();
}

public Loopy(IContaine r container)
{
container.Add(t his);

InitializeCompo nent();
}
}
}

Nov 17 '05 #1
2 1744
Don Tucker <Do*******@disc ussions.microso ft.com> wrote:
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 .v
80.en/dv_fxmclicc/html/7bc03b7b-d680-499b-8179-5f414b2d650c.ht m

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 experience is that the GUI is
locked up while each thread is running, though. I have a simple Windows App
form with 2 buttons, 2 text boxes, and 2 labels, and then a class called
Loopy (analogous to the walkthrough Calculator class) [attached below]. My
intention is to loop from 1 to N, where N in a number entered in a text box,
and then display the value of the loop variable on the GUI by updating a
label. Each button-textbox-label combo performs a different loop in a
separate thread. Is there a glaring error in the code or do I just have a
conceptual misunderstandin g?


I haven't got time to test it right now (I'm just about to leave) but I
suspect the problem is that you're doing a tight loop in your other
threads, so you don't give the UI thread a chance to get in. Put a call
to Thread.Sleep in while you're counting. That way you're much more
likely to be able to actually *see* the counting rather than it being a
blur, too :)

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

"Don Tucker" <Do*******@disc ussions.microso ft.com> wrote in message
news:11******** *************** ***********@mic rosoft.com...
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.ht m

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 experience is that the GUI
is
locked up while each thread is running, though. I have a simple Windows
App
form with 2 buttons, 2 text boxes, and 2 labels, and then a class called
Loopy (analogous to the walkthrough Calculator class) [attached below].
My
intention is to loop from 1 to N, where N in a number entered in a text
box,
and then display the value of the loop variable on the GUI by updating a
label. Each button-textbox-label combo performs a different loop in a
separate thread. Is there a glaring error in the code or do I just have a
conceptual misunderstandin g?


You shouldn't update the UI at that rate, first it makes no sense because
windows cannot paint at that rate, second you are flooding the UI thread
message queue with thousands of messages, the result is that the mouse and
KB becomes non-responsive.
If you click a mouse button or hit a key, the mouse message is simply
queued up behind the possibly thousands or more messages already in the
queue. This gives the illusion of a crashed app, because it's
non-responsive.
What you have to do is find a point in time when it's appropriate to update
the UI, for instance only after x iterations. Where x iterations do take
100-200msec. for instance, that way you only update a pace of 5 - 10 times a
second. Note that you might give up your thread quantum when doing the
update by calling Thread.Sleep(0) , this to make sure the UI thread gets a
chance to run when running a tight loop on a worker thread.

Some other remark is that you should avoid using "this" as a lock
(lock(this), in reality the lock isn't even needed as the variable you are
incrementing is not shared.

Willy.

Willy.

Nov 17 '05 #3

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

Similar topics

0
375
by: Steven Brown | last post by:
I'm trying to figure out how to safely use .NET events/delegates in a thread-safe class. There are a couple problems. One is that the standard "if(EventName != null) EventName(...);" call can fail if the event is emptied of all methods between the two statements, implying that some sort of synchronization between this and removals from EventName is needed. The other problem is that if an event with a set of delegates is in the process...
7
2703
by: Ivan | last post by:
Hi I have following problem: I'm creating two threads who are performing some tasks. When one thread finished I would like to restart her again (e.g. new job). Following example demonstrates that. Problem is that when program is started many threads are created (see output section), when only two should be running at any time. Can you please help me to identify me where the problem is? Best regards
4
3199
by: scott | last post by:
hi all, Thx to any one that can offer me help, it will be much appreciated. iv got a multithreaded program and need to use thread synchronization. The synchronization does not have to work across multiple processes just the one. I was wondering if any one new which one used the least overhead. Im at current using mutexes but was wondering if there was something a bit
20
2409
by: Bob Day | last post by:
Using VS 2003, VB, MSDE... There are two threads, A & B, that continously run and are started by Sub Main. They instantiationsl of identical code. Thread A handles call activity on telephone line 1 and Thread B handles call activity on telephone line 2. They use a common SQL datasource, but all DataSets are unique to each thread. Is there a way for thread A to occasionally communication to thread B that something has happened? ...
6
1418
by: Robert Speck | last post by:
Hi there, Can anyone shed anymore light on why "Thread.Suspend()" has been deprecated by MSFT beyond what MSDN says about it. I'm not sure if I quite appreciate the various pitfalls they discuss but using it under certain circumstances still seems reasonable. For instance, I want to display a small modal dialog with a "Cancel" button which allows the user to abort a background thread. If the user clicks this button, I then want to prompt...
4
1418
by: fniles | last post by:
I create a thread where I pass thru a message. When I click very fast many times (like 50 times) to create 50 threads, the message did not get pass thru ProcessMessage. For example: strBuffer = "#TRADE, D1410-123456, BUY, 1, ESM7, DAY, LIMIT, 1490.00, , , 0, 0, 0, 0, 0, links |52994/25/2007 10:47:17 AM !A", when I trigger to create many threads (like 50), this message did not get to sub ProcessMessage in clsEachMessage. I have added...
13
3601
by: arun.darra | last post by:
Are the following thread safe: 1. Assuming Object is any simple object Object* fn() { Object *p = new Object(); return p; } 2. is return by value thread safe?
0
1977
by: sundman.anders | last post by:
Hi all! I have a question about thread synchronization and c++ streams (iostreams, stringstreams, etc). When optimizing a program for a multicore processor I found that stringstream was causing a LOT of synchronization overhead. After a bit of digging I concluded that this synchronization has to do with the access to a global locale inside the stream. The problem can be seen by running the small distilled benchmark code
19
2309
by: Hapa | last post by:
Does only reading (never writing) of a variable need thread synchronisation? Thanks for help? PS. Anybody knows a Visual C++ news group?
8
1425
by: Markus | last post by:
Hello everyone. Recently I stumbled upon an interesting problem related to thread-parallel programming in C (and similarily C++). As an example assume a simple "buffer" array of size 8, e.g. with static lifetime and exteral linkage. One thread fills the buffer structure, and the other in some way evaluates its contents, e.g. do { synchronize_with_other_thread(); for (int i=0;i<8;++i) {
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
9111
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
8096
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...
0
6011
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
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
2
2634
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.