473,652 Members | 3,070 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

C#, Threads, Events, and DataGrids/DataSets

I am trying to run a thread off of a form, and every once in a while the thread will raise an event for the form to read. When the form gets the event, the form will place the event into a dataset and display it on a datagrid that is on the form. The problem is that the thread will slowly take over all of the processor time. After about 8 events, the form will not even respond anymore. Here is the guts of my test code

// Class and event for Threa
using System

namespace ThreadTestStuf

public delegate void TestEventHandle r(object sender,int count)
public class TestThread
public event TestEventHandle r TestEvent
public bool stopRunning = false
public TestThread(
{
public void RunningThread()
int xyz = 0
while (!stopRunning)
xyz += 1
Console.WriteLi ne("Count: " + xyz.ToString())
if (xyz % 1000 == 0)
TestEvent(this, xyz)



// Form that call the test threa
// Data set only has (int count) and (string desc) in i

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

namespace ThreadTes

public class ThreadTestForm : System.Windows. Forms.For

private ThreadTest.Test Set testSet1
private System.Windows. Forms.DataGrid TestDG
private System.Windows. Forms.Button StartThreadButt on
private Thread localThread
private TestThread localTestThread

private System.Componen tModel.Containe r components = null

public ThreadTestForm(

InitializeCompo nent()
protected override void Dispose( bool disposing
{
localTestThread .stopRunning = true
localThread.Abo rt()
if( disposing

if (components != null)

components.Disp ose()
base.Dispose( disposing )
private void InitializeCompo nent(

this.testSet1 = new ThreadTest.Test Set()
this.TestDG = new System.Windows. Forms.DataGrid( )
this.StartThrea dButton = new System.Windows. Forms.Button()
((System.Compon entModel.ISuppo rtInitialize)(t his.testSet1)). BeginInit()
((System.Compon entModel.ISuppo rtInitialize)(t his.TestDG)).Be ginInit()
this.SuspendLay out()
//
// testSet
//
this.testSet1.D ataSetName = "TestSet"
this.testSet1.L ocale = new System.Globaliz ation.CultureIn fo("en-US")
//
// TestD
//
this.TestDG.Dat aMember = ""
this.TestDG.Dat aSource = this.testSet1.T estTable
this.TestDG.Hea derForeColor = System.Drawing. SystemColors.Co ntrolText
this.TestDG.Loc ation = new System.Drawing. Point(16, 24)
this.TestDG.Nam e = "TestDG"
this.TestDG.Siz e = new System.Drawing. Size(320, 144)
this.TestDG.Tab Index = 0
//
// StartThreadButt o
//
this.StartThrea dButton.Locatio n = new System.Drawing. Point(224, 184)
this.StartThrea dButton.Name = "StartThreadBut ton"
this.StartThrea dButton.Size = new System.Drawing. Size(120, 32)
this.StartThrea dButton.TabInde x = 1
this.StartThrea dButton.Text = "Start Thread"
this.StartThrea dButton.Click += new System.EventHan dler(this.Start ThreadButton_Cl ick)
//
// ThreadTestFor
//
this.AutoScaleB aseSize = new System.Drawing. Size(5, 13)
this.ClientSize = new System.Drawing. Size(376, 253)
this.Controls.A dd(this.StartTh readButton)
this.Controls.A dd(this.TestDG)
this.Name = "ThreadTestForm "
this.Text = "Thread Test Form"
((System.Compon entModel.ISuppo rtInitialize)(t his.testSet1)). EndInit()
((System.Compon entModel.ISuppo rtInitialize)(t his.TestDG)).En dInit()
this.ResumeLayo ut(false)
#endregio

/// <summary
/// The main entry point for the application
/// </summary
[STAThread
static void Main()

Application.Run (new ThreadTestForm( ))

private void EventHappend(ob ject sender, int count

localThread.Int errupt()
testSet1.TestTa ble.AddTestTabl eRow(count,"Hel lo There")
// MessageBox.Show (localThread.Th readState.ToStr ing())
private void StartThreadButt on_Click(object sender, System.EventArg s e
{
localTestThread = new TestThread();
localTestThread .TestEvent += new TestEventHandle r(this.EventHap pend);
localThread = new Thread(new ThreadStart(loc alTestThread.Ru nningThread));
localThread.Sta rt();
localThread.IsB ackground = true;

}
}
}

Can anyone help?
Thanks,
Dennis Owens
Jul 21 '05 #1
28 1867
Dennis Owens <an*******@disc ussions.microso ft.com> wrote:
I am trying to run a thread off of a form, and every once in a while
the thread will raise an event for the form to read. When the form
gets the event, the form will place the event into a dataset and
display it on a datagrid that is on the form. The problem is that the
thread will slowly take over all of the processor time. After about 8
events, the form will not even respond anymore. Here is the guts of my
test code.


I'm not surprised - you've got 8 threads in a tight loop. That's bound
to take over the processor! However, you've got a few other nasties
going on...

Firstly, you're accessing stopRunning in a non-thread-safe way. You
should either declare it as being volatile, or wrap any access to it in
a lock.

Secondly, you should never update the GUI from a non-UI thread, as you
currently are doing. You should use Control.Invoke to invoke a delegate
on the UI thread.

Thirdly, why are you calling localThread.Int errupt() from your event?
At that time, you're actually running *in* the thread you're trying to
interrupt!

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Jul 21 '05 #2
The interrrupt was just a wild guess to try and stop it from sucking up all the processor time. I forgot I left it in there. The only line in that method should be the adding of the row in the dataset. As for your second thing, is this what is causing the thread to take over. Well I will lookup Control.Invoke and see if I can figure it out. I still don't see the eight threads, just the form and the test thread

Thanks Dennis Owen

Jul 21 '05 #3
Hi,
stopRunning doesn't need to be declared volatile and it should not be used
with locks.
Native integer assignment is atomic operation as well as native integer
promotion (even so the last doesn't even count).
No compiler would optimize away loading of cycle variable when there is
nontrivial cycle body (like non-inlined method calls inside of cycle).
And you don't need release/acquire semantic for single variable with atomic
assignment.
Using LOCK for accessing it would be unnecessary performance hit if not to
say a mistake.

I suppose that he misinterpreted meaning of Thread.Interrup t, and you are
correct with the rest of your comments.

-Valery.

See my blog at:
http://www.harper.no/valery

"Jon Skeet [C# MVP]" <sk***@pobox.co m> wrote in message
news:MP******** *************** *@msnews.micros oft.com...
Dennis Owens <an*******@disc ussions.microso ft.com> wrote:
I am trying to run a thread off of a form, and every once in a while
the thread will raise an event for the form to read. When the form
gets the event, the form will place the event into a dataset and
display it on a datagrid that is on the form. The problem is that the
thread will slowly take over all of the processor time. After about 8
events, the form will not even respond anymore. Here is the guts of my
test code.


I'm not surprised - you've got 8 threads in a tight loop. That's bound
to take over the processor! However, you've got a few other nasties
going on...

Firstly, you're accessing stopRunning in a non-thread-safe way. You
should either declare it as being volatile, or wrap any access to it in
a lock.

Secondly, you should never update the GUI from a non-UI thread, as you
currently are doing. You should use Control.Invoke to invoke a delegate
on the UI thread.

Thirdly, why are you calling localThread.Int errupt() from your event?
At that time, you're actually running *in* the thread you're trying to
interrupt!

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too

Jul 21 '05 #4
You have tight loop inside your thread method - of course it eats all
processor resources!
And btw, setting thread as background doesn't affect thread
priority/scheduling. it only says that .Net process can terminate even so
there are some background threads still running (I just think that you got
it wrong too)

and do as Jon said to you - use Invoke when you update controls from non-UI
threads.

-Valery

See my blog at:
http://www.harper.no/valery
"Dennis Owens" <an*******@disc ussions.microso ft.com> wrote in message
news:00******** *************** ***********@mic rosoft.com...
The interrrupt was just a wild guess to try and stop it from sucking up all the processor time. I forgot I left it in there. The only line in that
method should be the adding of the row in the dataset. As for your second
thing, is this what is causing the thread to take over. Well I will lookup
Control.Invoke and see if I can figure it out. I still don't see the eight
threads, just the form and the test thread?
Thanks Dennis Owens

Jul 21 '05 #5
Ok here is a simple question, how should this simple example be written

Thanks Dennis Owens
Jul 21 '05 #6
btw (for avoiding being misinterpreted) I didn't say that using bool flag as
thread event is good design :-). He should use kernel object like event for
signaling exit.

-Valery.

See my blog at:
http://www.harper.no/valery

"Valery Pryamikov" <Va****@nospam. harper.no> wrote in message
news:%2******** **********@TK2M SFTNGP09.phx.gb l...
Hi,
stopRunning doesn't need to be declared volatile and it should not be used
with locks.
Native integer assignment is atomic operation as well as native integer
promotion (even so the last doesn't even count).
No compiler would optimize away loading of cycle variable when there is
nontrivial cycle body (like non-inlined method calls inside of cycle).
And you don't need release/acquire semantic for single variable with atomic assignment.
Using LOCK for accessing it would be unnecessary performance hit if not to
say a mistake.

I suppose that he misinterpreted meaning of Thread.Interrup t, and you are
correct with the rest of your comments.

-Valery.

See my blog at:
http://www.harper.no/valery

"Jon Skeet [C# MVP]" <sk***@pobox.co m> wrote in message
news:MP******** *************** *@msnews.micros oft.com...
Dennis Owens <an*******@disc ussions.microso ft.com> wrote:
I am trying to run a thread off of a form, and every once in a while
the thread will raise an event for the form to read. When the form
gets the event, the form will place the event into a dataset and
display it on a datagrid that is on the form. The problem is that the
thread will slowly take over all of the processor time. After about 8
events, the form will not even respond anymore. Here is the guts of my
test code.


I'm not surprised - you've got 8 threads in a tight loop. That's bound
to take over the processor! However, you've got a few other nasties
going on...

Firstly, you're accessing stopRunning in a non-thread-safe way. You
should either declare it as being volatile, or wrap any access to it in
a lock.

Secondly, you should never update the GUI from a non-UI thread, as you
currently are doing. You should use Control.Invoke to invoke a delegate
on the UI thread.

Thirdly, why are you calling localThread.Int errupt() from your event?
At that time, you're actually running *in* the thread you're trying to
interrupt!

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too


Jul 21 '05 #7
Valery Pryamikov <Va****@nospam. harper.no> wrote:
stopRunning doesn't need to be declared volatile and it should not be used
with locks.
Native integer assignment is atomic operation as well as native integer
promotion (even so the last doesn't even count).


Being atomic has nothing to do with it. The memory model does not
guarantee that the running thread will *ever* see writes from another
thread unless a memory fence is involved.

You can argue about whether or not it'll actually happen, but I prefer
to work from guarantees when it comes to multi-threading - because
sooner or later, some architecture will come along and destroy all
assumptions apart from the guarantees.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Jul 21 '05 #8
Dennis Owens <an*******@disc ussions.microso ft.com> wrote:
The interrrupt was just a wild guess to try and stop it from sucking
up all the processor time. I forgot I left it in there. The only line
in that method should be the adding of the row in the dataset. As for
your second thing, is this what is causing the thread to take over.
Well I will lookup Control.Invoke and see if I can figure it out. I
still don't see the eight threads, just the form and the test thread?


Sorry, I thought you'd meant there were 8 clicks, not 8 events -
misread. Yup, there'll only be the one extra thread. It will still be
in a tight loop though, which is going to stuff you to some extent
*whatever* you do.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Jul 21 '05 #9
Valery Pryamikov <Va****@nospam. harper.no> wrote:
btw (for avoiding being misinterpreted) I didn't say that using bool flag as
thread event is good design :-). He should use kernel object like event for
signaling exit.


On the contrary, I'd say using a boolean (but using it properly) is a
perfectly reasonable way of exiting the thread. How would your code
with an event work? It's basically going to end up doing something
*equivalent* to just checking a flag, assuming that the thread wants to
keep doing work until it's told to stop.

Using a boolean is simple (when done right) and allows clean exit
(unlike, say, aborting the thread). Sure, it requires a memory barrier
in order to guarantee that the thread sees the appropriate change in
value, but those are very cheap in the grand scheme of things. What
benefit is there in doing anything else?

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Jul 21 '05 #10

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

Similar topics

2
1459
by: Marcel | last post by:
Hi, I'm new to VS and ASP.NET and have a question about master/detail datagrids. I have a master datagrid filled with data via a component that contains a SQL adapter. Now I would like to fill a detail datagrid (which will contain a number of detail records) based on the selected master. Is it possible to
0
1253
by: Scott Meddows | last post by:
I'm having trouble scrolling some datagrids so they sync up... I have two identical datagrids on a form, filled with eh same dataset. I want a user to be able to scroll on the datasets and the other dataset then scrolls to the same place on the other dataset (bare with me). This is the code that I have so far... Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load...
28
1734
by: Dennis Owens | last post by:
I am trying to run a thread off of a form, and every once in a while the thread will raise an event for the form to read. When the form gets the event, the form will place the event into a dataset and display it on a datagrid that is on the form. The problem is that the thread will slowly take over all of the processor time. After about 8 events, the form will not even respond anymore. Here is the guts of my test code // Class and event for...
6
1741
by: Steve Hershoff | last post by:
Hi everyone, I've got a strange one here. There are two datagrids on my page, one nested within the other. I'll refer to them as the topmost and secondary datagrids. In the topmost datagrid's OnItemDataBound() method we check for the row in which it's appropriate to add the secondary datagrid. Exactly one row in the topmost grid will contain the secondary grid.
0
8703
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8467
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8589
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6160
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5619
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4145
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4291
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1914
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1591
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.