473,811 Members | 2,963 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Threads and Events (form oddness)

This is my first time posting here, so please forgive me if I do anything
incorrectly.

I've been learning C# and working with different things and decided I wanted
to get into Multi-Threading. My problem is that I must not be doing it right
because only some of the stuff works as would be expected. I'll post what
exactly is happening, then I'll post the sample code I'm using that is
giving me the problems. I'm sure its something I've overlooked, or I'm just
doing it completely wrong.

Below is the code for my sample application. It has 2 buttons and a label.
Basically, the thread is just supposed to make the label visible and loop
every 5 seconds. the top button starts the thread going, and the bottom
button calls the Cancel() method which turns off blocking and allows the
thread to exit properly. The problem is that the label sometimes appears to
become visible, but if the form is minimized, or a window is moved over it,
you'll see its really not. Also.. the Form seems to become VERY laggy and
acts as though its processing REALLY hard (although its not as the
taskmanager says its using very little CPU).

You may ask why I'm using Events and that is because what I plan on doing is
making a worker thread that will send periodic updates back to the main
program to progress a status bar. Why I'm using threads and events isn't
important. What is important is that I must be doing something wrong, and I
want to learn how I should do it correctly.

Anyway.. that is my problem.. here is the source...
=============== ==============

using System;
using System.Drawing;
using System.Collecti ons;
using System.Componen tModel;
using System.Windows. Forms;
using System.Data;
using System.Threadin g;

namespace ThreadTest
{
#region TestEventHandle r
public delegate void TestEventHandle r(object sender, TestEventArgs e);
public class TestEventArgs : EventArgs
{
public bool ShowLabel = false;
public TestEventArgs(b ool bShowLabel) { ShowLabel = bShowLabel; }
}
#endregion
#region Test Thread
public class clsThreadTest
{
public event TestEventHandle r ShowLabel;
private bool blocked = false;
private Thread TestThread = null;
public clsThreadTest() { }
public void SetLabel(bool bVisible)
{
if (ShowLabel != null)
{
TestEventArgs tea = new TestEventArgs(b Visible);
ShowLabel(this, tea);
}
}
public void Start()
{
if (!blocked)
{
blocked = !blocked;
TestThread = new Thread(new ThreadStart(Run Test));
TestThread.Apar tmentState = ApartmentState. MTA;
TestThread.Prio rity = ThreadPriority. Lowest;
TestThread.Name = "Test Thread";
TestThread.Star t();
}
}

public void Cancel()
{
blocked = false;
}
public void RunTest()
{
while (blocked)
{
SetLabel(true);
Thread.Sleep(50 00);
}
}
}
#endregion
public class Form1 : System.Windows. Forms.Form
{
private clsThreadTest cThreadTest = new clsThreadTest() ;
private System.Windows. Forms.Label label1;
private System.Windows. Forms.Button button1;
private System.Windows. Forms.Button button2;
private System.Componen tModel.Containe r components = null;

public Form1()
{
InitializeCompo nent();
cThreadTest.Sho wLabel += new
TestEventHandle r(cThreadTest_S howLabel);

}

public void cThreadTest_Sho wLabel(object sender, TestEventArgs tea)
{
label1.Visible = tea.ShowLabel;
label1.Refresh( );
this.Refresh();
}

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.button1 = new System.Windows. Forms.Button();
this.button2 = new System.Windows. Forms.Button();
this.SuspendLay out();
//
// label1
//
this.label1.Fon t = new System.Drawing. Font("Microsoft Sans
Serif", 12F, System.Drawing. FontStyle.Bold,
System.Drawing. GraphicsUnit.Po int, ((System.Byte)( 0)));
this.label1.For eColor = System.Drawing. Color.Red;
this.label1.Loc ation = new System.Drawing. Point(42, 12);
this.label1.Nam e = "label1";
this.label1.Siz e = new System.Drawing. Size(108, 24);
this.label1.Tab Index = 0;
this.label1.Tex t = "Hello!";
this.label1.Tex tAlign =
System.Drawing. ContentAlignmen t.MiddleCenter;
this.label1.Vis ible = false;
//
// button1
//
this.button1.Lo cation = new System.Drawing. Point(186, 6);
this.button1.Na me = "button1";
this.button1.Si ze = new System.Drawing. Size(96, 18);
this.button1.Ta bIndex = 1;
this.button1.Te xt = "Start Thread";
this.button1.Cl ick += new
System.EventHan dler(this.butto n1_Click);
//
// button2
//
this.button2.Lo cation = new System.Drawing. Point(186, 24);
this.button2.Na me = "button2";
this.button2.Si ze = new System.Drawing. Size(96, 18);
this.button2.Ta bIndex = 2;
this.button2.Te xt = "Queue Stop";
this.button2.Cl ick += new
System.EventHan dler(this.butto n2_Click);
//
// Form1
//
this.AutoScaleB aseSize = new System.Drawing. Size(5, 13);
this.ClientSize = new System.Drawing. Size(292, 45);
this.Controls.A ddRange(new System.Windows. Forms.Control[] {

this.button2,

this.button1,

this.label1});
this.Name = "Form1";
this.Text = "Form1";
this.ResumeLayo ut(false);

}
#endregion

[STAThread]
static void Main()
{
Application.Run (new Form1());
}

private void button1_Click(o bject sender, System.EventArg s e)
{
cThreadTest.Sta rt();
}

private void button2_Click(o bject sender, System.EventArg s e)
{
cThreadTest.Can cel();
}
}
}
Nov 15 '05
10 4955
Awesome comments and code. Some of it went a little over me, but I'll
attempt a change toward what you suggested and see if I have any issues.

thank you for the input. It definately will help me. I now know that I'm not
allowed to call UI code from within a separate thread (even though it lets
me without really causing errors) and I kinda know how to fix it if I do.
Once again.. thanks for your help and I'll see if I can fix this up whe I
get back to work on Monday. =]

-Drak

"Michael Mayer" <mr*****@charte r.net> wrote in message
news:OL******** *****@TK2MSFTNG P11.phx.gbl...
I find win forms are easiest to write if they ONLY see the primary (or
UI) thread. Thus, all events (whether buttons clicks or "ShowLabel" )
can be treated the same. This means that your clsThreadTest needs to
synchronize the events it fires which would be consumed by a form (as
you've seen on another thread). I've put comments inline on this and
other things that caught my attention.

I'd be happy for any feedback.
mike

"Drakier Dominaeus" <dr*****@cox.ne t> wrote in message
news:S2FWa.2782 3$Je.9069@fed1r ead04...
=============== ==============


namespace ThreadTest
{

<snip>
#region Test Thread
public class clsThreadTest
{

I know this is just an example, but I don't like the name of this
event. It should be named on the verb of what is happenning or
happened in this class, not the expected action of another class.
Perhaps it should be "WorkStarti ng" or such. Then the SetLabel method
should be onWorkStarting( ). I guess the form should worry about
labels, this class should worry about doing work and saying things
like "starting", "halfwaydon e", "finished", etc.
public event TestEventHandle r ShowLabel;
private bool blocked = false;
private Thread TestThread = null;
public clsThreadTest() { }


I'd write the constructor as this, to hold a reference to the form
where you will invoke synchronized events. Note, I'm using the
ISynchronizeInv oke instead of just Control to keep it generic, even
though Control implements the interface. All we care about is that
the object provided can run synchronized events. Obviously, the form
class later needs to change the instantiation of this object.
// A target to invoke events on - mrm next 6 lines
private ISynchronizeInv oke target;

public clsThreadTest( ISynchronizeInv oke target)
{
this.target = target;
}

public void SetLabel(bool bVisible)
{
if (ShowLabel != null)
{
TestEventArgs tea = new TestEventArgs(b Visible);
ShowLabel(this, tea);

We can't throw an event from this thread and have the form update
controls. BAD.
Instead, we raise the ShowLabel event using the form's invoke method
(or we could use BeginInvoke, but I think this keeps it simpler).
So instead of the above single line, we have:
object[] paramList = {this, tea};
this.target.Inv oke(ShowLabel, paramList);
}
}
public void Start()
{

The following code scares me, cause it looks like it's calling for a
race condition. It all depends on where blocked can be set and who
all can call this function. What I mean is, generally doing a single
check and then assigning the value could lead to trouble. If there
were two threads out there, thread A could check blocked, then thread
B could check blocked, then thread A could set blocked, but thread B
is already in the procedure and running. In your specific case, since
the _only_ thread that would run this code is your UI thread, it's not
a problem. Even if the user has fast fingers and can hit Start twice
in a row very quickly, that would all happen on a single UI thread so
the order of execution for that one thread would be:
button click, call start(), return from start(), return to message
loop, button click #2, call start() and find blocked is true.
I'd still be tempted to put a lock on the whole function:
lock (myLockObject)
// where myLockObject is a private object for locking on
//(e.g. private Object myLockObject)
{
if (!blocked)
{
blocked = !blocked;

i'd rewrite the above line to just assign true. I think it's what you
really mean: if we want to start and are not blocked, then block and
continue. You're not technically wanting to _reverse_ the block. (as
a start/stop toggle method might do?)

blocked = true;
TestThread = new Thread(new

ThreadStart(Run Test));
TestThread.Apar tmentState = ApartmentState. MTA;
TestThread.Prio rity = ThreadPriority. Lowest;
TestThread.Name = "Test Thread";
TestThread.Star t();
}

} // end lock(this)
}

public void Cancel()
{
blocked = false;
}

I like this method of canceling, personally (as opposed to the
ManualResetEven t). KISS. I don't see any threading problems since a
boolean is set in one autonomous write. It's also the method used by
Griffiths in an article I posted in another message on this thread.
public void RunTest()
{
while (blocked)
{
SetLabel(true);
Thread.Sleep(50 00);

I assume Thread.Sleep is where the "work" goes.
}
}
}
#endregion

public class Form1 : System.Windows. Forms.Form
{
private clsThreadTest cThreadTest;
private System.Windows. Forms.Label label1;
private System.Windows. Forms.Button button1;
private System.Windows. Forms.Button button2;
private System.Componen tModel.Containe r components = null;

public Form1()
{
InitializeCompo nent();


Need to give clsThreadTest a reference to this form.
cThreadTest = = new clsThreadTest(t his);
cThreadTest.Sho wLabel += new
TestEventHandle r(cThreadTest_S howLabel);

}

<snip>
everything else is fine by me.

Nov 15 '05 #11

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

Similar topics

1
1436
by: Jerry J | last post by:
I'm trying to understand how many threads are involved when a client event handler is called. I am using a simple .net windows application. I click a button on a form that triggers an event. The event delegate calls two event handlers in two seperate object instances. Are the event handlers getting called sequentially relative to the main thread or are seperate threads being generated to handle the events?
0
2124
by: Drakier Dominaeus | last post by:
This is my first time posting here, so please forgive me if I do anything incorrectly. I've been learning C# and working with different things and decided I wanted to get into Multi-Threading. My problem is that I must not be doing it right because only some of the stuff works as would be expected. I'll post what exactly is happening, then I'll post the sample code I'm using that is giving me the problems. I'm sure its something I've...
10
2785
by: J.Marsch | last post by:
I know that the controls on a Winform are not thread safe, and that you want to do all of your UI updates on a single thread -- generally the main thread. Now, 2 questions: 1. Does the one thread that you can use to update controls have to be the thread that you were on when you instanced the form? 2. Can 2 forms in the same application have affinity for different threads, or do you want all of the forms in an application to be...
3
506
by: Jacob | last post by:
I'm working on a class that needs to be called from a windows form, do it's work, and then, show progress back to the main form. I'm well aware that worker threads need to call Invoke for updates to the main thread to be threadsafe. I want to make this worker class I'm writing a self contained assembly so that other's can drop it into their projects. My question is: How can I NOT force those implementing my class to have to call...
22
4076
by: Jeff Louie | last post by:
Well I wonder if my old brain can handle threading. Dose this code look reasonable. Regards, Jeff using System; using System.Diagnostics; using System.IO; using System.Threading;
2
1010
by: Richard Bell | last post by:
I'm working on a VB.net app that uses IE, some forms, and multiple execution threads. I'm unclear on a couple of threading related matters and hoped that someone could provide some insight. From within a thread of execution, if I do a form.show, what thread does the form process execute on? Is the form process supported by its own thread? When the form post an event that my code catches such as a button press, what thread does the...
15
2614
by: Bryce K. Nielsen | last post by:
I have an object that starts a thread to do a "process". One of the steps inside this thread launches 12 other threads via a Delegate.BeginInvoke to process. After these 12 threads are launched, the main thread waits. At the completion of each subthread, the mainthread checks all 12 thread objects to see if they are done. If they are, raise an event that says we're done. So, it's kinda like this: ProcessThread - Creates a ProcessObject
4
4022
by: gsimmons | last post by:
I've been researching multi-threaded WinForms apps and thread synchronization stuff for a couple days since I'm working on refactoring a multi-threaded GUI app at work and want to be sure it's rock solid/thread-safe. I've seen all the posts about using BeginInvoke to have worker threads interact with the UI. My question is this: I created a plain old Windows Form application (VS.NET 2005) with a blank form, built it (release build), ran...
9
2111
by: thiago777 | last post by:
Question details: VB .NET / threads / events / GUI Imagine the following situation: A method from object "A" creates "n" threads. Variables from these threads contains values that should be updated to a form (only when this form exists), one form can be shown/created for each thread. Thought the forms might not exist, the threads will be always running. I dont want to control the components (eg. labels) of the form from the threads...
0
9603
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
10379
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...
1
10393
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10124
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...
1
7664
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
5690
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4334
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
3863
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3015
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 effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.