473,799 Members | 3,817 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 #1
10 4952
A couple things stick out.

1. You cannot update UI elements from any thread other than the one
that created the UI element. Since your form was created on the
Primary thread, only the primary thread can update the form and/or
it's child controls. Doing so from another thread leads to
inconsistent results at best.

You would have to use Control.Invoke to synchronously call your
delegate on the other thread or Control.BeginIn voke to asynchronously
call it.

Also, your method of cancelling the secondary thread is really not the
appropriate way to go. Consider using a ManualResetEven t and a
WaitOne call in your loop. When your Cancel button is clicked, set
the event. In your loop processing, you do a

// Assume ev is a ManualResetEven t

while (true)
{
if (ev.WaitOne(500 0))
breakl // event was signalled

... // do other stuff here
}

You can create the ManualResetEven t in your Form and pass it as a
parameter to your "Thread" class.

Jonathan Schafer
On Fri, 1 Aug 2003 19:08:53 -0700, "Drakier Dominaeus"
<dr*****@cox.ne t> wrote:
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
TestEventHandl er(cThreadTest_ ShowLabel);

}

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.P oint, ((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 .ContentAlignme nt.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.EventHa ndler(this.butt on1_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.EventHa ndler(this.butt on2_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 #2
A couple things stick out.

1. You cannot update UI elements from any thread other than the one
that created the UI element. Since your form was created on the
Primary thread, only the primary thread can update the form and/or
it's child controls. Doing so from another thread leads to
inconsistent results at best.

You would have to use Control.Invoke to synchronously call your
delegate on the other thread or Control.BeginIn voke to asynchronously
call it.

Also, your method of cancelling the secondary thread is really not the
appropriate way to go. Consider using a ManualResetEven t and a
WaitOne call in your loop. When your Cancel button is clicked, set
the event. In your loop processing, you do a

// Assume ev is a ManualResetEven t

while (true)
{
if (ev.WaitOne(500 0))
breakl // event was signalled

... // do other stuff here
}

You can create the ManualResetEven t in your Form and pass it as a
parameter to your "Thread" class.

Jonathan Schafer
On Fri, 1 Aug 2003 19:08:53 -0700, "Drakier Dominaeus"
<dr*****@cox.ne t> wrote:
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
TestEventHandl er(cThreadTest_ ShowLabel);

}

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.P oint, ((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 .ContentAlignme nt.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.EventHa ndler(this.butt on1_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.EventHa ndler(this.butt on2_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 #3
I'm not sure how the ManualResetEven ts work. I've never used them before, so
I'm not sure what they are, or how they are used. If you could explain that
a little, and maybe include some of my source code modified to how it should
be, I think I'll understand it a bit better in context. From another thread,
I learned that I cannot control UI elements from other threads, and someone
else suggested I could use Invoke. I mainly want to know the proper method
so that I can learn right the first time and not get into bad habits.

-Drakier

"Jonathan Schafer" <jschafer@*NOSP AM*brierley.a.b .c.com> wrote in message
news:45******** *************** *********@4ax.c om...
A couple things stick out.

1. You cannot update UI elements from any thread other than the one
that created the UI element. Since your form was created on the
Primary thread, only the primary thread can update the form and/or
it's child controls. Doing so from another thread leads to
inconsistent results at best.

You would have to use Control.Invoke to synchronously call your
delegate on the other thread or Control.BeginIn voke to asynchronously
call it.

Also, your method of cancelling the secondary thread is really not the
appropriate way to go. Consider using a ManualResetEven t and a
WaitOne call in your loop. When your Cancel button is clicked, set
the event. In your loop processing, you do a

// Assume ev is a ManualResetEven t

while (true)
{
if (ev.WaitOne(500 0))
breakl // event was signalled

... // do other stuff here
}

You can create the ManualResetEven t in your Form and pass it as a
parameter to your "Thread" class.

Jonathan Schafer
On Fri, 1 Aug 2003 19:08:53 -0700, "Drakier Dominaeus"
<dr*****@cox.ne t> wrote:
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 wantedto get into Multi-Threading. My problem is that I must not be doing it rightbecause 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 justdoing 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 tobecome 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 ismaking 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 Iwant 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
TestEventHandl er(cThreadTest_ ShowLabel);

}

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.P oint, ((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 .ContentAlignme nt.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.EventHa ndler(this.butt on1_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.EventHa ndler(this.butt on2_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 #4
I'm not sure how the ManualResetEven ts work. I've never used them before, so
I'm not sure what they are, or how they are used. If you could explain that
a little, and maybe include some of my source code modified to how it should
be, I think I'll understand it a bit better in context. From another thread,
I learned that I cannot control UI elements from other threads, and someone
else suggested I could use Invoke. I mainly want to know the proper method
so that I can learn right the first time and not get into bad habits.

-Drakier

"Jonathan Schafer" <jschafer@*NOSP AM*brierley.a.b .c.com> wrote in message
news:45******** *************** *********@4ax.c om...
A couple things stick out.

1. You cannot update UI elements from any thread other than the one
that created the UI element. Since your form was created on the
Primary thread, only the primary thread can update the form and/or
it's child controls. Doing so from another thread leads to
inconsistent results at best.

You would have to use Control.Invoke to synchronously call your
delegate on the other thread or Control.BeginIn voke to asynchronously
call it.

Also, your method of cancelling the secondary thread is really not the
appropriate way to go. Consider using a ManualResetEven t and a
WaitOne call in your loop. When your Cancel button is clicked, set
the event. In your loop processing, you do a

// Assume ev is a ManualResetEven t

while (true)
{
if (ev.WaitOne(500 0))
breakl // event was signalled

... // do other stuff here
}

You can create the ManualResetEven t in your Form and pass it as a
parameter to your "Thread" class.

Jonathan Schafer
On Fri, 1 Aug 2003 19:08:53 -0700, "Drakier Dominaeus"
<dr*****@cox.ne t> wrote:
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 wantedto get into Multi-Threading. My problem is that I must not be doing it rightbecause 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 justdoing 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 tobecome 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 ismaking 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 Iwant 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
TestEventHandl er(cThreadTest_ ShowLabel);

}

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.P oint, ((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 .ContentAlignme nt.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.EventHa ndler(this.butt on1_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.EventHa ndler(this.butt on2_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 #5
Have a look at this article. I *HIGHLY* recommend it.
http://msdn.microsoft.com/msdnmag/is...g/default.aspx

It talks all about how to do multithreading with windows forms
controls. And it provides a great base class in the download
(AsyncOperation in Listing2 I believe) that you can inherit from to
create your own worker thread that can fire events back to a windows
forms, and a nice way to cancel the worker thread. I believe it will
provide everything you need, plus explain it much better than I could
do here. If you have any questions while / after reading the article
and looking at his code, I'd be more than happy to discuss here, as
would others on the ng.

Good luck,
Mike

"Drakier Dominaeus" <dr*****@cox.ne t> wrote in message
news:ejHWa.2784 7$Je.23698@fed1 read04...
I'm not sure how the ManualResetEven ts work. I've never used them before, so I'm not sure what they are, or how they are used. If you could explain that a little, and maybe include some of my source code modified to how it should be, I think I'll understand it a bit better in context. From another thread, I learned that I cannot control UI elements from other threads, and someone else suggested I could use Invoke. I mainly want to know the proper method so that I can learn right the first time and not get into bad habits.
-Drakier

"Jonathan Schafer" <jschafer@*NOSP AM*brierley.a.b .c.com> wrote in message news:45******** *************** *********@4ax.c om...
A couple things stick out.

1. You cannot update UI elements from any thread other than the one
that created the UI element. Since your form was created on the
Primary thread, only the primary thread can update the form and/or
it's child controls. Doing so from another thread leads to
inconsistent results at best.

You would have to use Control.Invoke to synchronously call your
delegate on the other thread or Control.BeginIn voke to asynchronously call it.

Also, your method of cancelling the secondary thread is really not the appropriate way to go. Consider using a ManualResetEven t and a
WaitOne call in your loop. When your Cancel button is clicked, set the event. In your loop processing, you do a

// Assume ev is a ManualResetEven t

while (true)
{
if (ev.WaitOne(500 0))
breakl // event was signalled

... // do other stuff here
}

You can create the ManualResetEven t in your Form and pass it as a
parameter to your "Thread" class.

Jonathan Schafer
On Fri, 1 Aug 2003 19:08:53 -0700, "Drakier Dominaeus"
<dr*****@cox.ne t> wrote:
This is my first time posting here, so please forgive me if I do anythingincorrectly.

I've been learning C# and working with different things and decided I
wantedto get into Multi-Threading. My problem is that I must not be
doing it
rightbecause only some of the stuff works as would be expected. I'll
post whatexactly is happening, then I'll post the sample code I'm using that isgiving me the problems. I'm sure its something I've overlooked, or I'm
justdoing 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 loopevery 5 seconds. the top button starts the thread going, and the bottombutton calls the Cancel() method which turns off blocking and allows thethread to exit properly. The problem is that the label sometimes appears
tobecome 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 andacts as though its processing REALLY hard (although its not as thetaskmanager says its using very little CPU).

You may ask why I'm using Events and that is because what I plan on doing
ismaking a worker thread that will send periodic updates back to
the mainprogram to progress a status bar. Why I'm using threads and events isn'timportant. What is important is that I must be doing something wrong, and
Iwant 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
TestEventHandl er(cThreadTest_ ShowLabel);

}

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 SansSerif", 12F, System.Drawing. FontStyle.Bold,
System.Drawing .GraphicsUnit.P oint, ((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 .ContentAlignme nt.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.EventHa ndler(this.butt on1_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.EventHa ndler(this.butt on2_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 #6
Have a look at this article. I *HIGHLY* recommend it.
http://msdn.microsoft.com/msdnmag/is...g/default.aspx

It talks all about how to do multithreading with windows forms
controls. And it provides a great base class in the download
(AsyncOperation in Listing2 I believe) that you can inherit from to
create your own worker thread that can fire events back to a windows
forms, and a nice way to cancel the worker thread. I believe it will
provide everything you need, plus explain it much better than I could
do here. If you have any questions while / after reading the article
and looking at his code, I'd be more than happy to discuss here, as
would others on the ng.

Good luck,
Mike

"Drakier Dominaeus" <dr*****@cox.ne t> wrote in message
news:ejHWa.2784 7$Je.23698@fed1 read04...
I'm not sure how the ManualResetEven ts work. I've never used them before, so I'm not sure what they are, or how they are used. If you could explain that a little, and maybe include some of my source code modified to how it should be, I think I'll understand it a bit better in context. From another thread, I learned that I cannot control UI elements from other threads, and someone else suggested I could use Invoke. I mainly want to know the proper method so that I can learn right the first time and not get into bad habits.
-Drakier

"Jonathan Schafer" <jschafer@*NOSP AM*brierley.a.b .c.com> wrote in message news:45******** *************** *********@4ax.c om...
A couple things stick out.

1. You cannot update UI elements from any thread other than the one
that created the UI element. Since your form was created on the
Primary thread, only the primary thread can update the form and/or
it's child controls. Doing so from another thread leads to
inconsistent results at best.

You would have to use Control.Invoke to synchronously call your
delegate on the other thread or Control.BeginIn voke to asynchronously call it.

Also, your method of cancelling the secondary thread is really not the appropriate way to go. Consider using a ManualResetEven t and a
WaitOne call in your loop. When your Cancel button is clicked, set the event. In your loop processing, you do a

// Assume ev is a ManualResetEven t

while (true)
{
if (ev.WaitOne(500 0))
breakl // event was signalled

... // do other stuff here
}

You can create the ManualResetEven t in your Form and pass it as a
parameter to your "Thread" class.

Jonathan Schafer
On Fri, 1 Aug 2003 19:08:53 -0700, "Drakier Dominaeus"
<dr*****@cox.ne t> wrote:
This is my first time posting here, so please forgive me if I do anythingincorrectly.

I've been learning C# and working with different things and decided I
wantedto get into Multi-Threading. My problem is that I must not be
doing it
rightbecause only some of the stuff works as would be expected. I'll
post whatexactly is happening, then I'll post the sample code I'm using that isgiving me the problems. I'm sure its something I've overlooked, or I'm
justdoing 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 loopevery 5 seconds. the top button starts the thread going, and the bottombutton calls the Cancel() method which turns off blocking and allows thethread to exit properly. The problem is that the label sometimes appears
tobecome 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 andacts as though its processing REALLY hard (although its not as thetaskmanager says its using very little CPU).

You may ask why I'm using Events and that is because what I plan on doing
ismaking a worker thread that will send periodic updates back to
the mainprogram to progress a status bar. Why I'm using threads and events isn'timportant. What is important is that I must be doing something wrong, and
Iwant 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
TestEventHandl er(cThreadTest_ ShowLabel);

}

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 SansSerif", 12F, System.Drawing. FontStyle.Bold,
System.Drawing .GraphicsUnit.P oint, ((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 .ContentAlignme nt.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.EventHa ndler(this.butt on1_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.EventHa ndler(this.butt on2_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 #7
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 #8
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 #9
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 #10

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

Similar topics

1
1435
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
2784
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
4073
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
2609
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
4020
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
9687
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
9543
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
10488
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
10257
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
10237
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
6808
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
4144
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
3761
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2941
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.