Threads and Events (form oddness)

  • Thread starter Drakier Dominaeus
  • Start date
D

Drakier Dominaeus

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.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Threading;

namespace ThreadTest
{
#region TestEventHandler
public delegate void TestEventHandler(object sender, TestEventArgs e);
public class TestEventArgs : EventArgs
{
public bool ShowLabel = false;
public TestEventArgs(bool bShowLabel) { ShowLabel = bShowLabel; }
}
#endregion
#region Test Thread
public class clsThreadTest
{
public event TestEventHandler ShowLabel;
private bool blocked = false;
private Thread TestThread = null;
public clsThreadTest() { }
public void SetLabel(bool bVisible)
{
if (ShowLabel != null)
{
TestEventArgs tea = new TestEventArgs(bVisible);
ShowLabel(this, tea);
}
}
public void Start()
{
if (!blocked)
{
blocked = !blocked;
TestThread = new Thread(new ThreadStart(RunTest));
TestThread.ApartmentState = ApartmentState.MTA;
TestThread.Priority = ThreadPriority.Lowest;
TestThread.Name = "Test Thread";
TestThread.Start();
}
}

public void Cancel()
{
blocked = false;
}
public void RunTest()
{
while (blocked)
{
SetLabel(true);
Thread.Sleep(5000);
}
}
}
#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.ComponentModel.Container components = null;

public Form1()
{
InitializeComponent();
cThreadTest.ShowLabel += new
TestEventHandler(cThreadTest_ShowLabel);

}

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

protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
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 InitializeComponent()
{
this.label1 = new System.Windows.Forms.Label();
this.button1 = new System.Windows.Forms.Button();
this.button2 = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// label1
//
this.label1.Font = new System.Drawing.Font("Microsoft Sans
Serif", 12F, System.Drawing.FontStyle.Bold,
System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this.label1.ForeColor = System.Drawing.Color.Red;
this.label1.Location = new System.Drawing.Point(42, 12);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(108, 24);
this.label1.TabIndex = 0;
this.label1.Text = "Hello!";
this.label1.TextAlign =
System.Drawing.ContentAlignment.MiddleCenter;
this.label1.Visible = false;
//
// button1
//
this.button1.Location = new System.Drawing.Point(186, 6);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(96, 18);
this.button1.TabIndex = 1;
this.button1.Text = "Start Thread";
this.button1.Click += new
System.EventHandler(this.button1_Click);
//
// button2
//
this.button2.Location = new System.Drawing.Point(186, 24);
this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size(96, 18);
this.button2.TabIndex = 2;
this.button2.Text = "Queue Stop";
this.button2.Click += new
System.EventHandler(this.button2_Click);
//
// Form1
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(292, 45);
this.Controls.AddRange(new System.Windows.Forms.Control[] {

this.button2,

this.button1,

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

}
#endregion

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

private void button1_Click(object sender, System.EventArgs e)
{
cThreadTest.Start();
}

private void button2_Click(object sender, System.EventArgs e)
{
cThreadTest.Cancel();
}
}
}
 
J

Jonathan Schafer

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.BeginInvoke to asynchronously
call it.

Also, your method of cancelling the secondary thread is really not the
appropriate way to go. Consider using a ManualResetEvent 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 ManualResetEvent

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

... // do other stuff here
}

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

Jonathan Schafer


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.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Threading;

namespace ThreadTest
{
#region TestEventHandler
public delegate void TestEventHandler(object sender, TestEventArgs e);
public class TestEventArgs : EventArgs
{
public bool ShowLabel = false;
public TestEventArgs(bool bShowLabel) { ShowLabel = bShowLabel; }
}
#endregion
#region Test Thread
public class clsThreadTest
{
public event TestEventHandler ShowLabel;
private bool blocked = false;
private Thread TestThread = null;
public clsThreadTest() { }
public void SetLabel(bool bVisible)
{
if (ShowLabel != null)
{
TestEventArgs tea = new TestEventArgs(bVisible);
ShowLabel(this, tea);
}
}
public void Start()
{
if (!blocked)
{
blocked = !blocked;
TestThread = new Thread(new ThreadStart(RunTest));
TestThread.ApartmentState = ApartmentState.MTA;
TestThread.Priority = ThreadPriority.Lowest;
TestThread.Name = "Test Thread";
TestThread.Start();
}
}

public void Cancel()
{
blocked = false;
}
public void RunTest()
{
while (blocked)
{
SetLabel(true);
Thread.Sleep(5000);
}
}
}
#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.ComponentModel.Container components = null;

public Form1()
{
InitializeComponent();
cThreadTest.ShowLabel += new
TestEventHandler(cThreadTest_ShowLabel);

}

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

protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
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 InitializeComponent()
{
this.label1 = new System.Windows.Forms.Label();
this.button1 = new System.Windows.Forms.Button();
this.button2 = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// label1
//
this.label1.Font = new System.Drawing.Font("Microsoft Sans
Serif", 12F, System.Drawing.FontStyle.Bold,
System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this.label1.ForeColor = System.Drawing.Color.Red;
this.label1.Location = new System.Drawing.Point(42, 12);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(108, 24);
this.label1.TabIndex = 0;
this.label1.Text = "Hello!";
this.label1.TextAlign =
System.Drawing.ContentAlignment.MiddleCenter;
this.label1.Visible = false;
//
// button1
//
this.button1.Location = new System.Drawing.Point(186, 6);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(96, 18);
this.button1.TabIndex = 1;
this.button1.Text = "Start Thread";
this.button1.Click += new
System.EventHandler(this.button1_Click);
//
// button2
//
this.button2.Location = new System.Drawing.Point(186, 24);
this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size(96, 18);
this.button2.TabIndex = 2;
this.button2.Text = "Queue Stop";
this.button2.Click += new
System.EventHandler(this.button2_Click);
//
// Form1
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(292, 45);
this.Controls.AddRange(new System.Windows.Forms.Control[] {

this.button2,

this.button1,

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

}
#endregion

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

private void button1_Click(object sender, System.EventArgs e)
{
cThreadTest.Start();
}

private void button2_Click(object sender, System.EventArgs e)
{
cThreadTest.Cancel();
}
}
}
 
D

Drakier Dominaeus

I'm not sure how the ManualResetEvents 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 said:
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.BeginInvoke to asynchronously
call it.

Also, your method of cancelling the secondary thread is really not the
appropriate way to go. Consider using a ManualResetEvent 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 ManualResetEvent

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

... // do other stuff here
}

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

Jonathan Schafer


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.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Threading;

namespace ThreadTest
{
#region TestEventHandler
public delegate void TestEventHandler(object sender, TestEventArgs e);
public class TestEventArgs : EventArgs
{
public bool ShowLabel = false;
public TestEventArgs(bool bShowLabel) { ShowLabel = bShowLabel; }
}
#endregion
#region Test Thread
public class clsThreadTest
{
public event TestEventHandler ShowLabel;
private bool blocked = false;
private Thread TestThread = null;
public clsThreadTest() { }
public void SetLabel(bool bVisible)
{
if (ShowLabel != null)
{
TestEventArgs tea = new TestEventArgs(bVisible);
ShowLabel(this, tea);
}
}
public void Start()
{
if (!blocked)
{
blocked = !blocked;
TestThread = new Thread(new ThreadStart(RunTest));
TestThread.ApartmentState = ApartmentState.MTA;
TestThread.Priority = ThreadPriority.Lowest;
TestThread.Name = "Test Thread";
TestThread.Start();
}
}

public void Cancel()
{
blocked = false;
}
public void RunTest()
{
while (blocked)
{
SetLabel(true);
Thread.Sleep(5000);
}
}
}
#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.ComponentModel.Container components = null;

public Form1()
{
InitializeComponent();
cThreadTest.ShowLabel += new
TestEventHandler(cThreadTest_ShowLabel);

}

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

protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
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 InitializeComponent()
{
this.label1 = new System.Windows.Forms.Label();
this.button1 = new System.Windows.Forms.Button();
this.button2 = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// label1
//
this.label1.Font = new System.Drawing.Font("Microsoft Sans
Serif", 12F, System.Drawing.FontStyle.Bold,
System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this.label1.ForeColor = System.Drawing.Color.Red;
this.label1.Location = new System.Drawing.Point(42, 12);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(108, 24);
this.label1.TabIndex = 0;
this.label1.Text = "Hello!";
this.label1.TextAlign =
System.Drawing.ContentAlignment.MiddleCenter;
this.label1.Visible = false;
//
// button1
//
this.button1.Location = new System.Drawing.Point(186, 6);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(96, 18);
this.button1.TabIndex = 1;
this.button1.Text = "Start Thread";
this.button1.Click += new
System.EventHandler(this.button1_Click);
//
// button2
//
this.button2.Location = new System.Drawing.Point(186, 24);
this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size(96, 18);
this.button2.TabIndex = 2;
this.button2.Text = "Queue Stop";
this.button2.Click += new
System.EventHandler(this.button2_Click);
//
// Form1
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(292, 45);
this.Controls.AddRange(new System.Windows.Forms.Control[] {

this.button2,

this.button1,

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

}
#endregion

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

private void button1_Click(object sender, System.EventArgs e)
{
cThreadTest.Start();
}

private void button2_Click(object sender, System.EventArgs e)
{
cThreadTest.Cancel();
}
}
}
 
M

Michael Mayer

Have a look at this article. I *HIGHLY* recommend it.
http://msdn.microsoft.com/msdnmag/issues/03/02/Multithreading/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 said:
I'm not sure how the ManualResetEvents 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

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.BeginInvoke to asynchronously
call it.

Also, your method of cancelling the secondary thread is really not the
appropriate way to go. Consider using a ManualResetEvent 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 ManualResetEvent

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

... // do other stuff here
}

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

Jonathan Schafer
decided I
wanted doing it
right or I'm
just a
appears
moved over
it, on doing
is wrong, and
I TestEventArgs
TestEventArgs
tea)
{
label1.Visible = tea.ShowLabel;
label1.Refresh();
this.Refresh();
}

protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
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 InitializeComponent()
{
this.label1 = new System.Windows.Forms.Label();
this.button1 = new System.Windows.Forms.Button();
this.button2 = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// label1
//
this.label1.Font = new System.Drawing.Font("Microsoft Sans
Serif", 12F, System.Drawing.FontStyle.Bold,
System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this.label1.ForeColor = System.Drawing.Color.Red;
this.label1.Location = new System.Drawing.Point(42, 12);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(108, 24);
this.label1.TabIndex = 0;
this.label1.Text = "Hello!";
this.label1.TextAlign =
System.Drawing.ContentAlignment.MiddleCenter;
this.label1.Visible = false;
//
// button1
//
this.button1.Location = new System.Drawing.Point(186, 6);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(96, 18);
this.button1.TabIndex = 1;
this.button1.Text = "Start Thread";
this.button1.Click += new
System.EventHandler(this.button1_Click);
//
// button2
//
this.button2.Location = new System.Drawing.Point(186, 24);
this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size(96, 18);
this.button2.TabIndex = 2;
this.button2.Text = "Queue Stop";
this.button2.Click += new
System.EventHandler(this.button2_Click);
//
// Form1
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(292, 45);
this.Controls.AddRange(new System.Windows.Forms.Control[] {

this.button2,

this.button1,

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

}
#endregion

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

private void button1_Click(object sender, System.EventArgs e)
{
cThreadTest.Start();
}

private void button2_Click(object sender, System.EventArgs e)
{
cThreadTest.Cancel();
}
}
}
 
M

Michael Mayer

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 said:
=============================

namespace ThreadTest
{
#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 "WorkStarting" 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", "halfwaydone", "finished", etc.
public event TestEventHandler 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
ISynchronizeInvoke 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 ISynchronizeInvoke target;

public clsThreadTest( ISynchronizeInvoke target)
{
this.target = target;
}

public void SetLabel(bool bVisible)
{
if (ShowLabel != null)
{
TestEventArgs tea = new TestEventArgs(bVisible);
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.Invoke(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(RunTest));
TestThread.ApartmentState = ApartmentState.MTA;
TestThread.Priority = ThreadPriority.Lowest;
TestThread.Name = "Test Thread";
TestThread.Start();
} } // end lock(this)
}

public void Cancel()
{
blocked = false;
}
I like this method of canceling, personally (as opposed to the
ManualResetEvent). 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(5000);
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.ComponentModel.Container components = null;

public Form1()
{
InitializeComponent();

Need to give clsThreadTest a reference to this form.
cThreadTest = = new clsThreadTest(this);
cThreadTest.ShowLabel += new
TestEventHandler(cThreadTest_ShowLabel);

}
<snip>
everything else is fine by me.
 
D

Drakier Dominaeus

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 said:
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 said:
=============================

namespace ThreadTest
{
#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 "WorkStarting" 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", "halfwaydone", "finished", etc.
public event TestEventHandler 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
ISynchronizeInvoke 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 ISynchronizeInvoke target;

public clsThreadTest( ISynchronizeInvoke target)
{
this.target = target;
}

public void SetLabel(bool bVisible)
{
if (ShowLabel != null)
{
TestEventArgs tea = new TestEventArgs(bVisible);
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.Invoke(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(RunTest));
TestThread.ApartmentState = ApartmentState.MTA;
TestThread.Priority = ThreadPriority.Lowest;
TestThread.Name = "Test Thread";
TestThread.Start();
} } // end lock(this)
}

public void Cancel()
{
blocked = false;
}
I like this method of canceling, personally (as opposed to the
ManualResetEvent). 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(5000);
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.ComponentModel.Container components = null;

public Form1()
{
InitializeComponent();

Need to give clsThreadTest a reference to this form.
cThreadTest = = new clsThreadTest(this);
cThreadTest.ShowLabel += new
TestEventHandler(cThreadTest_ShowLabel);

}
<snip>
everything else is fine by me.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top