New to .net threads

  • Thread starter Thread starter Wayne
  • Start date Start date
W

Wayne

I am writing my first .net thread, I need it to run until it is told to
stop. The thread will process records from a database table, sleep for x
milliseconds. I have all of that working, the issue I have is knowing when
the thread has been informed that it needs to stop. I've found Thread.Abort,
but that appears to cause the thread to exit right away and not let the
thread control when it will exit.

In Delphi I would have done the following:

Thread Code
while not (self.Terminated) do
begin
ReadDatabase;
Sleep(time);
end;

Main Code
Thread.Terminate;

Thread.Terminate would set Terminated to true thus causing the while loop to
exit normally from the thread. How would I duplicate this in .net?
--
Thanks
Wayne Sepega
Jacksonville, Fl

Enterprise Library Configuration Console Module Generator
http://workspaces.gotdotnet.com/elccmg

"When a man sits with a pretty girl for an hour, it seems like a minute. But
let him sit on a hot stove for a minute and it's longer than any hour.
That's relativity." - Albert Einstein
 
You can do the same thing you are doing now. Use a boolean flag instead of
Self.Terminated. When you set it to true the thread will finish whatever it's
processing and then exit.
 
Wayne said:
I am writing my first .net thread, I need it to run until it is told to
stop. The thread will process records from a database table, sleep for x
milliseconds. I have all of that working, the issue I have is knowing when
the thread has been informed that it needs to stop. I've found Thread.Abort,
but that appears to cause the thread to exit right away and not let the
thread control when it will exit.

In Delphi I would have done the following:

Thread Code
while not (self.Terminated) do
begin
ReadDatabase;
Sleep(time);
end;

Main Code
Thread.Terminate;

Thread.Terminate would set Terminated to true thus causing the while loop to
exit normally from the thread. How would I duplicate this in .net?

See http://www.pobox.com/~skeet/csharp/threads/shutdown.shtml
 
Wayne said:
In Delphi I would have done the following:

Thread Code
while not (self.Terminated) do
begin
ReadDatabase;
Sleep(time);
end;

Main Code
Thread.Terminate;

Thread.Terminate would set Terminated to true thus causing the while loop to
exit normally from the thread. How would I duplicate this in .net?

Following is another way of doing this.

class Worker
{
volatile bool stopping = false;

public void Stop() {
stopping = true;
}

[...]

void ThreadJob() {
while (!stopping) {
DoSomething();
}
}
}

Note the *volatile* flag. See
<http://www.yoda.arachsys.com/csharp/threads/volatility.shtml> for
rationale.
 
Back
Top