473,324 Members | 2,313 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,324 software developers and data experts.

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.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 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 misunderstanding?

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

public Form1()
{
InitializeComponent();
Loopy1 = new Loopy();
Loopy1.Loop1Working += new
Loopy.Loop1WorkingHandler(this.Loop1WHandler);
Loopy1.Loop2Working += new
Loopy.Loop2WorkingHandler(this.Loop2WHandler);
Loopy1.Loop1Complete += new
Loopy.Loop1CompleteHandler(this.Loop1CHandler);
Loopy1.Loop2Complete += new
Loopy.Loop2CompleteHandler(this.Loop2CHandler);
}

private void button1_Click(object sender, EventArgs e)
{
Loopy1.var1 = int.Parse(textBox1.Text);
// Disables the btnFactorial1 until this calculation is complete.
button1.Enabled = false;
Loopy1.ChooseThreads(1);
}

private void button2_Click(object sender, EventArgs e)
{
Loopy1.var2 = int.Parse(textBox2.Text);
// Disables the btnFactorial1 until this calculation is complete.
button2.Enabled = false;
Loopy1.ChooseThreads(2);
}

protected void Loop1WHandler(int current)
// Displays the returned value in the appropriate label.
{
this.BeginInvoke(new LoopWHandler(L1WHandler), new Object[] {
current });
}

protected void Loop2WHandler(int current)
{
this.BeginInvoke(new LoopWHandler(L2WHandler), new Object[] {
current });
}

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

protected void Loop2CHandler()
{
this.BeginInvoke(new LoopCHandler(L2CHandler), new Object[] {});
}

public void L1WHandler(int current)
{
label1.Text = current.ToString();
}
public void L2WHandler(int current)
{
label2.Text = current.ToString();
}
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 Loop1WorkingHandler(int current);
public delegate void Loop2WorkingHandler(int current);
public delegate void Loop1CompleteHandler();
public delegate void Loop2CompleteHandler();

public event Loop1WorkingHandler Loop1Working;
public event Loop2WorkingHandler Loop2Working;
public event Loop1CompleteHandler Loop1Complete;
public event Loop2CompleteHandler Loop2Complete;

public System.Threading.Thread Loop1Thread;
public System.Threading.Thread Loop2Thread;

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

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

public void ChooseThreads(int 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.Threading.Thread(new
System.Threading.ThreadStart(this.Loop1));
// Starts the thread.
Loop1Thread.Start();
break;
case 2:
Loop2Thread = new
System.Threading.Thread(new
System.Threading.ThreadStart(this.Loop2));
Loop2Thread.Start();
break;
}
}

public Loopy()
{
InitializeComponent();
}

public Loopy(IContainer container)
{
container.Add(this);

InitializeComponent();
}
}
}

Nov 17 '05 #1
2 1729
Don Tucker <Do*******@discussions.microsoft.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.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 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 misunderstanding?


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.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #2

"Don Tucker" <Do*******@discussions.microsoft.com> wrote in message
news:11**********************************@microsof t.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.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 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 misunderstanding?


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
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...
7
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...
4
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...
20
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...
6
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...
4
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 =...
13
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
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...
19
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
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....
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...

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.