Threading Question - New to Thread !!!

  • Thread starter msnews.microsoft.com
  • Start date
M

msnews.microsoft.com

Hi All,

I have the following code. If the MessageBox.Show statement is enabled then
the "GetDataTableThread" is being started or else its state remains as
unstarted.

What should I do to start the GetDataTableThread Thread and make sure it is
started?

Any suggestions please?

Thanks for your time

Regards
Anand Ganesh

//////// Code Starts //////////////

this.richTextBoxMessage.Text = "" ;
Thread GetDataTableThread = new Thread(new
ThreadStart(InvokeGetDataTableThread)) ;
GetDataTableThread.Start() ;
//MessageBox.Show("This is main Thread!");
while(!GetDataTableThread.IsAlive) ;
this.richTextBoxMessage.Text = this.richTextBoxMessage.Text + "\n" + "Main
Thread State = " + Thread.CurrentThread.ThreadState.ToString() ;
this.richTextBoxMessage.Text = this.richTextBoxMessage.Text + "\n" +
"GetDataTableThread State = " + GetDataTableThread.ThreadState.ToString() ;
GetDataTableThread.Abort() ;
this.richTextBoxMessage.Text = this.richTextBoxMessage.Text + "\n" + "Thread
aborted!" ;
GetDataTableThread.Join() ;

//////// Code Ends //////////////
 
P

Pete Davis

You probably want to replace this:

while(!GetDataTableThread.IsAlive) ;

with:

while(!GetDataTableThread.IsAlive)
{
Thread.Sleep(50);
}

Otherwise your main thread is going to hog the CPU, and that may be keeping
the other thread from getting started. Just a possibility.

Pete

or something.
 
J

Jon Skeet [C# MVP]

msnews.microsoft.com said:
I have the following code. If the MessageBox.Show statement is enabled then
the "GetDataTableThread" is being started or else its state remains as
unstarted.

What should I do to start the GetDataTableThread Thread and make sure it is
started?

For one thing, get rid of your tight loop (the while loop). Tight loops
are never a good idea.
 
M

msnews.microsoft.com

Hi Pete / Jon,

Thanks a lot for sparing your time to help me out.

I added a sleep(1000) without the while loop and it works as expected.

The Child Thread is always getting started.

Now in the same code I am getting another difficulty which is not clear for
me.

GetDataTableThread.Join() ;

This line is throwing an exception which I am not able to understand.

Does it mean I should not call Join at all?

Is it enough if I simply abort the thread?

Can you please explain what this exception means?

Thanks
Anand Ganesh
 
M

msnews.microsoft.com

Hi Pete / Jon,

Thanks a lot for sparing your time to help me out.

I added a sleep(1000) without the while loop and it works as expected.

The Child Thread is always getting started.

Now in the same code I am getting another difficulty which is not clear for
me.

GetDataTableThread.Join() ;

This line is throwing an exception which I am not able to understand.

Does it mean I should not call Join at all?

Is it enough if I simply abort the thread?

Can you please explain what this exception means?

Thanks
Anand Ganesh





Jon Skeet said:
For one thing, get rid of your tight loop (the while loop). Tight loops
are never a good idea.
 
M

msnews.microsoft.com

Hi All,

Actually I am getting the following Exception

"Object reference not set to an instance of an object."

Is it beacuse the GetDataTableThread was aborted this is causing the error?

I am actaully following a Micrsoft Sample. Here is the link

http://msdn.microsoft.com/library/d...y/en-us/csref/html/vcwlkThreadingTutorial.asp

Here you can see how the oThread.Join() is called after oThread.Abort().

Is it possible there is a typo in the Sample? Should it be Thread.Join() ?

Can someone please explain?

Thanks for your time.

Regards
Anand Ganesh



msnews.microsoft.com said:
Hi Pete / Jon,

Thanks a lot for sparing your time to help me out.

I added a sleep(1000) without the while loop and it works as expected.

The Child Thread is always getting started.

Now in the same code I am getting another difficulty which is not clear
for
me.

GetDataTableThread.Join() ;

This line is throwing an exception which I am not able to understand.

Does it mean I should not call Join at all?

Is it enough if I simply abort the thread?

Can you please explain what this exception means?

Thanks
Anand Ganesh





Jon Skeet said:
For one thing, get rid of your tight loop (the while loop). Tight loops
are never a good idea.
 
J

Jon Skeet [C# MVP]

msnews.microsoft.com said:
Actually I am getting the following Exception

"Object reference not set to an instance of an object."

Is it beacuse the GetDataTableThread was aborted this is causing the error?

I am actaully following a Micrsoft Sample. Here is the link

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/csre
f/html/vcwlkThreadingTutorial.asp

Here you can see how the oThread.Join() is called after oThread.Abort().

Are you sure the exception is happening in that thread, and not in
GetDataTableThread?

Could you post a short but complete program which demonstrates the
problem?

See http://www.pobox.com/~skeet/csharp/complete.html for details of
what I mean by that.
Is it possible there is a typo in the Sample? Should it be Thread.Join() ?

No - Thread.Join isn't a static method.
 
M

msnews.microsoft.com

Hi Jon,

I created a simple program and I am back to the same initial problem.
The child Thread is not at all starting. Any suggestions Please?


//////////// Sample Starts ////////////////////

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Threading ;
namespace ThreadTest

{
/// <summary>
/// Summary description for Form1.
/// </summary>
public class Form1 : System.Windows.Forms.Form
{
private System.Windows.Forms.Button button1;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;

public Form1()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
//
// TODO: Add any constructor code after InitializeComponent call
//
}

/// <summary>
/// Clean up any resources being used.
/// </summary>
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.button1 = new System.Windows.Forms.Button();
this.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// button1
//
this.button1.Location = new System.Drawing.Point(224, 16);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(216, 23);
this.button1.TabIndex = 0;
this.button1.Text = "Click button to start the Child Thread";
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// label1
//
this.label1.Location = new System.Drawing.Point(24, 56);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(624, 23);
this.label1.TabIndex = 1;
this.label1.Text = "label1";
//
// label2
//
this.label2.Location = new System.Drawing.Point(24, 104);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(624, 23);
this.label2.TabIndex = 2;
this.label2.Text = "label2";
//
// Form1
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(672, 149);
this.Controls.Add(this.label2);
this.Controls.Add(this.label1);
this.Controls.Add(this.button1);
this.Name = "Form1";
this.Text = "Form1";
this.ResumeLayout(false);
}
#endregion
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]

static void Main()
{
Application.Run(new Form1());
}
private void button1_Click(object sender, System.EventArgs e)
{
try
{
this.label1.Text = "" ;
Thread GetDataTableThread = new Thread(new
ThreadStart(InvokeGetDataTableThread)) ;
GetDataTableThread.Start() ;
Thread.Sleep(1000) ;
this.label1.Text = "This is main Thread is going to Sleep !";
this.label1.Refresh() ;
//MessageBox.Show("ok") ;
GetDataTableThread.Abort() ;
this.label1.Text = this.label1.Text + "Again going to Sleep !";
this.label1.Refresh() ;
Thread.Sleep(1000) ;
GetDataTableThread.Join() ;
}

catch(Exception ex)
{
MessageBox.Show(ex.ToString()," Error in function DisplayDataValues") ;
}
}


void InvokeGetDataTableThread()
{
this.label2.Text = "Control is in the Child Thread !" ;
this.label2.Refresh() ;
}
}
}

//////////// Sample Ends ////////////////////


Thanks for your time.

Regards
Anand Ganesh
 
M

msnews.microsoft.com

Thanks Jon,

I think at this point let me tell my core problem and I hope you can provide
a solution.

I have a windows form which displays a DataTable but it will only show first
500 records.

There is a button called "Complete List". If the user clicks it, it will
fetch all the records. But if the database is too big it takes a long time.

So if the user changes the mind I want him to hit another button and cancel
the record fetching process.

So to fetch the record I will be running one thread and when the user clicks
on the cancel button I want to abort that thread.

So I guess my design was wrong or I cannot do this with threads in the
Windows Form.

Can you please suggest something to resolve this problem?

Thanks for being so kind and spending time in resolving my issue.

Regards
Anand Ganesh
 
J

Jon Skeet [C# MVP]

msnews.microsoft.com said:
I think at this point let me tell my core problem and I hope you can provide
a solution.

I have a windows form which displays a DataTable but it will only show first
500 records.

There is a button called "Complete List". If the user clicks it, it will
fetch all the records. But if the database is too big it takes a long time.

So if the user changes the mind I want him to hit another button and cancel
the record fetching process.

So to fetch the record I will be running one thread and when the user clicks
on the cancel button I want to abort that thread.

I wouldn't use Abort myself - I'm pretty much against calling
Thread.Abort, as it can leave threads in unexpected states.
So I guess my design was wrong or I cannot do this with threads in the
Windows Form.

Can you please suggest something to resolve this problem?

Thanks for being so kind and spending time in resolving my issue.

I suggest you do the database access in another thread, periodically
polling a flag to see whether or not the action has been cancelled by
the user. You also then use the techniques described in the link in my
previous post to make sure you only change the UI in the UI thread.
 
M

msnews.microsoft.com

Hi Jon,
I wouldn't use Abort myself - I'm pretty much against calling
Thread.Abort, as it can leave threads in unexpected states.

What is the right way to cancel the Thread, If I don't use Abort? For
example in my case the user wants to cancel the data fetch?

Thanks
Anand Ganesh
 
J

Jon Skeet [C# MVP]

msnews.microsoft.com said:
What is the right way to cancel the Thread, If I don't use Abort? For
example in my case the user wants to cancel the data fetch?

As I said, periodically test a flag and just stop fetching if the flag
indicates that the user has cancelled the operation.

Now, if you're using DataAdapter.Fill, there is indeed a problem - you
need a way of exiting during that call. One way you *could* do this,
although it's not very nice, is to add a row handler to the DataTable
which will be fired every time a row is added. Within that handler, you
could test the flag and then throw an exception (nasty, i know) if the
flag is set. It's a shame MS don't provide (as far as I know, anyway) a
way of cancelling a call to DataAdapter.Fill.
 
M

msnews.microsoft.com

Hi Jon,

Thanks for the help and suggestions.

Discussing with you was very good.

Also your article on Threading was good.

Even though you claim you are not master in this subject but I look you as
the MASTER.

Thanks again and happy holidays.

Regards
Anand Ganesh
 
J

Josh Ross

You can cancel a DataAdapter.Fill by killing its SPID serverside on
another thread. Just make sure that your app is logged in as an admin,
on the sql server, and that you handle the exception from the fill.
 
J

jhgon smith

How to become a millionare.Turn $6.00 into $60,000...read this to find
out how!!! READING THIS COULD CHANGE YOUR LIFE!!! I found this on a
bulletin board like this one and decided to try it. A little while back,
I was browsing through a newsgroup, just like you are now, and came
across an article similar to this that said you could make thousands of
dollars within weeks with only an initial investment of $6.00! So I
thought, "Yeah right, this must be a scam", but like most of us, I was
curious, so I kept reading. Anyway, it said that you need to send $1.00
to each of the 6 names and address stated in the article. You then place
your own name and address in the bottom of the list at #6, and post the
article in at least 200 newsgroups. (There are thousands) No catch, that
was it. So after thinking it over, and talking to a few people first, I
thought about trying it. I figured "what have I got to lose except 6
stamps and $6.00, right?" Then I invested the measly $6.00 (I use the
word "measly" because $6 really is measly compared to the money I have
made through the initial investment). Well GUESS WHAT!!... within 7
days, I started getting money in the mail! I was shocked! I figured it
would end soon, but the money just kept coming in. In my first week, I
made about $25.00. By the end of the second week I had made a total of
over $1,000.00! In the third week I had over $10,000.00 and it's still
growing. This is now my fourth week and I have made just over $42,000.00
and it's still coming in rapidly. It's certainly worth $6.00, and 6
stamps, I have spent more than that on the lottery!! Let me tell you how
this works and most importantly, why it works.... Also, make sure you
print a copy of this article NOW, so you can get the information off of
it as you need it. I promise you that if you follow the directions
exactly, that you will start making more money than you thought possible
by doing something so easy! Suggestion: Read this entire message
carefully! (print it out or download it.) Follow the simple directions
and watch the money come in! It's easy. It's legal. And, your investment
is only $6.00 (Plus postage) IMPORTANT: This is not a rip-off; it is not
indecent; it is not illegal; and it is virtually no risk - it really
works!!!! If all of the following instructions are adhered to, you will
receive extraordinary dividends. PLEASE NOTE: Please follow these
directions EXACTLY, and $50,000 or more can be yours in 20 to 60 days.
This program remains successful because of the honesty and integrity of
the participants. Please continue it’s success by carefully adhering to
the instructions. You will now become part of the Mail Order business.
In this business your product is not solid and tangible, it's a service.
You are in the business of developing Mailing Lists. Many large
corporations are happy to pay big bucks for quality lists. However, the
money made from the mailing lists is secondary to the income which is
made from people like you and me asking to be included in that list.
Here are the 4 easy steps to success: STEP 1: Get 6 separate pieces of
paper and write the following on each piece of paper "PLEASE PUT ME ON
YOUR MAILING LIST." Now get 6 US $1.00 bills and place ONE inside EACH
of the 6 pieces of paper so the bill will not be seen through the
envelope (to prevent thievery). Next, place one paper in each of the 6
envelopes and seal them. You should now have 6 sealed envelopes, each
with a piece of paper stating the phrase "PLEASE PUT ME ON YOUR MAILING
LIST.", your name and address, and a $1.00 bill. What you are doing is
creating a service. THIS IS ABSOLUTELY LEGAL! You are requesting a
legitimate service and you are paying for it! Like most of us I was a
little skeptical and a little worried about the legal aspects of it all.
So I checked it out with the U.S. Post Office (1-800-725-2161) and they
confirmed that it is indeed legal! Mail the 6 envelopes to the following
addresses: #1)Alfonso Gonzalez 727 E. San Ysidro Blvd. #714 San Ysidro,
CA 92173 #2)Richonda Scott CMR 402 BOX 274 APO, AE 09180 #3)Kaiba
Bennett 409 Ardmore Dr. Trenton, OH 45067 #4)Keagan Polk P.O. Box 581
Elberta, AL 36530 #5) Brandon Ford 727 Carriage Hills Court Martinez,
GA 30907 #6) Jhon Smith 14907sw 80st apt.106, Fl 33193. STEP 2: Now take
the #1 name off the list that you see above, move the other names up (6
becomes 5, 5 becomes 4, etc...) and add YOUR Name as number 6 on the
list. STEP 3: Change anything you need to, but try to keep this article
as close to original as possible. Now, post your amended article to at
least 200 newsgroups. (I think there are close to 32,000+) All you need
is 200, but remember, the more you post, the more money you make! This
is perfectly legal! If you have any doubts, refer to Title 18 Sec. 1302
& 1341 of the Postal lottery laws. Keep a copy of these steps for
yourself and, whenever you need money, you can use it again, and again.
PLEASE REMEMBER that this program remains successful because of the
honesty and integrity of the participants and by their carefully
adhering to the directions. Look at it this way. If you are of
integrity, the program will continue and the money that so many others
have received will come your way. NOTE: You may want to retain every
name and address sent to you, either on a computer or hard copy and keep
the notes people send you. This VERIFIES that you are truly providing a
service. (Also, it might be a good idea to wrap the $1 bill in dark
paper to reduce the risk of mail theft.) So, as each post is downloaded
and the directions carefully followed, six members will be reimbursed
for their participation as a List Developer with one dollar each. Your
name will move up the list geometrically so that when your name reaches
the #1 position you will be receiving thousands of dollars in CASH!!!
What an opportunity for only $6.00 ($1.00 for each of the first six
people listed above) Send it now, add your own name to the list and
you're in business! ---DIRECTIONS ----- FOR HOW TO POST TO
NEWSGROUPS------------ Step 1) You do not need to re-type this entire
letter to do your own posting. Simply put your cursor at the beginning
of this letter and drag your cursor to the bottom of this document, and
select 'copy' from the edit menu. This will copy the entire letter into
the computer's memory. Step 2) Open a blank 'notepad' file and place
your cursor at the top of the blank page. From the 'edit' menu select
'paste'. This will paste a copy of the letter into notepad so that you
can add your name to the list. Step 3) Save your new notepad file as a
.txt file. If you want to do your postings in different settings, you'll
always have this file to go back to. Step 4) Use Netscape or Internet
explorer and try searching for various newsgroups (on-line forums,
message boards, chat sites, discussions, etc.) Step 5) Visit these
message boards and post this article as a new message by highlighting
the text of this letter and selecting paste from the edit menu. Fill in
the Subject, this will be the header that everyone sees as they scroll
through the list of postings in a particular group, click the post
message button. You're done with your first one!
Congratulations...THAT'S IT! All you have to do is jump to different
newsgroups and post away, after you get the hang of it, it will take
about 30 seconds for each newsgroup! **REMEMBER, THE MORE NEWSGROUPS YOU
POST IN, THE MORE MONEY YOU WILL MAKE!! BUT YOU HAVE TO POST A MINIMUM
OF 200** That's it! You will begin receiving money from around the world
within days! You may eventually want to rent a P.O.Box due to the large
amount of mail you will receive. If you wish to stay anonymous, you can
invent a name to use, as long as the postman will deliver it. **JUST
MAKE SURE ALL THE ADDRESSES ARE CORRECT.** Now the WHY part: Out of 200
postings, say I receive only 5 replies (a very low example). So then I
made $5.00 with my name at #6 on the letter. Now, each of the 5 persons
who just sent me $1.00 make the MINIMUM 200 postings, each with my name
at #5 and only 5 persons respond to each of the original 5, that is
another $25.00 for me, now those 25 each make 200 MINIMUM posts with my
name at #4 and only 5 replies each, I will bring in an additional
$125.00! Now, those 125 persons turn around and post the MINIMUM 200
with my name at #3 and only receive 5 replies each, I will make an
additional $626.00! OK, now here is the fun part, each of those 625
persons post a MINIMUM 200 letters with my name at #2 and they each only
receive 5 replies, that just made me $3,125.00!!! Those 3,125 persons
will all deliver this message to 200 newsgroups with my name at #1 and
if still ONLY 5 persons per 200 newsgroups react I will receive
$15,625,00! With an original investment of only $6.00! AMAZING! When
your name is no longer on the list, you just take the latest posting in
the newsgroups, and send out another $6.00 to names on the list, putting
your name at number 6 again. And start posting again. The thing to
remember is do you realize that thousands of people all over the world
are joining the internet and reading these articles everyday?, JUST LIKE
YOU are now!! So, can you afford $6.00 and see if it really works??
Almost anyone can!! Remember,read this entire message very carefully,
and follow the EXACT instructions that are given, and this will really
work!!!
 

Ask a Question

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

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

Ask a Question

Top