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();
}
}
} 10 4906
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
On Fri, 1 Aug 2003 19:08:53 -0700, "Drakier Dominaeus"
<dr*****@cox.net> 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.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(); } } }
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
On Fri, 1 Aug 2003 19:08:53 -0700, "Drakier Dominaeus"
<dr*****@cox.net> 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.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(); } } }
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" <jschafer@*NOSPAM*brierley.a.b.c.com> wrote in message
news:45********************************@4ax.com... 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
On Fri, 1 Aug 2003 19:08:53 -0700, "Drakier Dominaeus" <dr*****@cox.net> 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.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(); } } }
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" <jschafer@*NOSPAM*brierley.a.b.c.com> wrote in message
news:45********************************@4ax.com... 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
On Fri, 1 Aug 2003 19:08:53 -0700, "Drakier Dominaeus" <dr*****@cox.net> 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.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(); } } }
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.net> wrote in message
news:ejHWa.27847$Je.23698@fed1read04... 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" <jschafer@*NOSPAM*brierley.a.b.c.com> wrote in
message news:45********************************@4ax.com... 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
On Fri, 1 Aug 2003 19:08:53 -0700, "Drakier Dominaeus" <dr*****@cox.net> 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.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 SansSerif", 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(); } } }
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.net> wrote in message
news:ejHWa.27847$Je.23698@fed1read04... 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" <jschafer@*NOSPAM*brierley.a.b.c.com> wrote in
message news:45********************************@4ax.com... 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
On Fri, 1 Aug 2003 19:08:53 -0700, "Drakier Dominaeus" <dr*****@cox.net> 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.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 SansSerif", 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(); } } }
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.net> wrote in message
news:S2FWa.27823$Je.9069@fed1read04... =============================
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 "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.
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.net> wrote in message
news:S2FWa.27823$Je.9069@fed1read04... =============================
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 "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.
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*****@charter.net> wrote in message
news:OL*************@TK2MSFTNGP11.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.net> wrote in message news:S2FWa.27823$Je.9069@fed1read04... =============================
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 "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.
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*****@charter.net> wrote in message
news:OL*************@TK2MSFTNGP11.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.net> wrote in message news:S2FWa.27823$Je.9069@fed1read04... =============================
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 "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.
This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics
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. ...
|
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....
|
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...
|
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...
|
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;
|
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.
...
|
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,...
|
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...
|
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...
|
by: ryjfgjl |
last post by:
ExcelToDatabase: batch import excel into database automatically...
|
by: isladogs |
last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM).
In this month's session, we are pleased to welcome back...
|
by: Vimpel783 |
last post by:
Hello!
Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
|
by: jfyes |
last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
|
by: ArrayDB |
last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
|
by: Defcon1945 |
last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
|
by: af34tf |
last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
|
by: Faith0G |
last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
|
by: isladogs |
last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM).
In this session, we are pleased to welcome former...
| |