473,320 Members | 1,719 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

Thread.Suspend()

Hi,

I'm using a second thread within my program to do some long
calculations, without locking up the UI:

worker = new Thread(new ThreadStart(myClass.Run));
worker.Start();

I want to be able to pause the calculating, so I'm using

worker.Suspend()
and
worker.Resume()

I'm not using any shared variables or such like resources which need to
be protected/mutex but the compiler is telling me that these two
commands are obsolete/depreciated, yet they both still function.

Is there a newer (better) way I should be doing this, or am I OK to be
using these?

Thanks

Andrew
Feb 19 '06 #1
12 31810
On Sun, 19 Feb 2006 15:08:57 GMT, Andrew Bullock
<an*********************@ANDntlworldTHIS.com> wrote:
Is there a newer (better) way I should be doing this, or am I OK to be
using these?


You shouldn't use them because they're dangerous, though I don't
recall the details at the moment. There's no newer alternative way
either, you just have to use manual synchronization -- check for some
semaphore on the worker thread and go to sleep if it's set.
--
http://www.kynosarges.de
Feb 19 '06 #2
Hi Andrew,
using suspend on a thread is generally considered a bad idea because if
you stop a thread in mid execution you can run into deadlock and race
conditions. What if a thread is suspended inside a critical region, nothing
else will be able to access that region etc. A better way to handle thread
syncronization is through WaitHandles. They act like barriers to thread
execution, threads cannot pass through the WaitHandle until another thread
open the handle allowing the thread to pass through. There are two basic
flavours, AutoResetEvent which will close the handle (go from Signalled to
Unsignalled) once a single thread passes through, and the ManualResetEvent
which once set will allow multiple threads to pass until it is manually reset.

Here is an example where a worker thread is allowed to do some processing
but then must wait for the main Thread to signal to it that it can complete
the final part of its processing:

using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

namespace ConsoleApplication18
{
class Program
{
static void Main(string[] args)
{
AutoResetEvent waitHandle = new AutoResetEvent(false);

//start other thread
Worker worker = new Worker();
worker.DoSomeWork(waitHandle);

//let main UI thread so some processing
Console.WriteLine("Main thread working");
Thread.Sleep(5000);

Console.WriteLine("Main thread finished work, let other thread
continue");
waitHandle.Set();

Console.ReadLine();
}
}

class Worker
{
private WaitHandle waitHandle;

public void DoSomeWork(WaitHandle waitHandle)
{
this.waitHandle = waitHandle;

Thread t = new Thread(new ThreadStart(ProcessValues));
t.Start();
}

private void ProcessValues()
{
//Can run this anytime
for (int i = 0; i < 5; i++)
{
Console.WriteLine("processing:" + i);
}

//make sure I am allowed to keep going
this.waitHandle.WaitOne();

//Can only run this once main thread is happy
for (int i = 0; i < 5; i++)
{
Console.WriteLine("last processing:" + i);
}
}
}
}
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

namespace ConsoleApplication18
{
class Program
{
static void Main(string[] args)
{
AutoResetEvent waitHandle = new AutoResetEvent(false);

//start other thread
Worker worker = new Worker();
worker.DoSomeWork(waitHandle);

//let main UI thread so some processing
Console.WriteLine("Main thread working");
Thread.Sleep(5000);

Console.WriteLine("Main thread finished work, let other thread
continue");
waitHandle.Set();

Console.ReadLine();
}
}

class Worker
{
private WaitHandle waitHandle;

public void DoSomeWork(WaitHandle waitHandle)
{
this.waitHandle = waitHandle;

Thread t = new Thread(new ThreadStart(ProcessValues));
t.Start();
}

private void ProcessValues()
{
//Can run this anytime
for (int i = 0; i < 5; i++)
{
Console.WriteLine("processing:" + i);
}

//make sure I am allowed to keep going
this.waitHandle.WaitOne();

//Can only run this once main thread is happy
for (int i = 0; i < 5; i++)
{
Console.WriteLine("last processing:" + i);
}
}
}
}

Hope that helps
Mark Dawson

--
http://www.markdawson.org
"Andrew Bullock" wrote:
Hi,

I'm using a second thread within my program to do some long
calculations, without locking up the UI:

worker = new Thread(new ThreadStart(myClass.Run));
worker.Start();

I want to be able to pause the calculating, so I'm using

worker.Suspend()
and
worker.Resume()

I'm not using any shared variables or such like resources which need to
be protected/mutex but the compiler is telling me that these two
commands are obsolete/depreciated, yet they both still function.

Is there a newer (better) way I should be doing this, or am I OK to be
using these?

Thanks

Andrew

Feb 19 '06 #3
Its always a good idea to try to know why you are not suppose to do
something, rather than just accepting a blanket statement, otherwise how do
you know when not to do it. Not looking into these things will lead to
comments like "Throwing Exceptions are expensive, don't ever throw them" or
"Never concatenate strings, always use a string builder" :-)

Mark.
--
http://www.markdawson.org
"Christoph Nahr" wrote:
On Sun, 19 Feb 2006 15:08:57 GMT, Andrew Bullock
<an*********************@ANDntlworldTHIS.com> wrote:
Is there a newer (better) way I should be doing this, or am I OK to be
using these?


You shouldn't use them because they're dangerous, though I don't
recall the details at the moment. There's no newer alternative way
either, you just have to use manual synchronization -- check for some
semaphore on the worker thread and go to sleep if it's set.
--
http://www.kynosarges.de

Feb 19 '06 #4

Using Suspend is not good idea, use ManualResetEvent as was suggested by
Christofer.
Moreover, Thread.Suspend() is obsolete in .NET 2.0

AB> I'm using a second thread within my program to do some long
AB> calculations, without locking up the UI:
AB>
AB> worker = new Thread(new ThreadStart(myClass.Run)); worker.Start();
AB>
AB> I want to be able to pause the calculating, so I'm using
AB>
AB> worker.Suspend()
AB> and
AB> worker.Resume()
AB> I'm not using any shared variables or such like resources which need
AB> to be protected/mutex but the compiler is telling me that these two
AB> commands are obsolete/depreciated, yet they both still function.
AB>
AB> Is there a newer (better) way I should be doing this, or am I OK to
AB> be using these?

---
WBR,
Michael Nemtsev :: blog: http://spaces.msn.com/laflour

"At times one remains faithful to a cause only because its opponents do not
cease to be insipid." (c) Friedrich Nietzsche
Feb 19 '06 #5
On Sun, 19 Feb 2006 15:49:16 +0000 (UTC), Michael Nemtsev
<ne*****@msn.com> wrote:
Using Suspend is not good idea, use ManualResetEvent as was suggested by
Christofer.


Actually, that was Mark. :)'
--
http://www.kynosarges.de
Feb 19 '06 #6
Mark R. Dawson wrote:
<snip>

private void ProcessValues()
{
//Can run this anytime
for (int i = 0; i < 5; i++)
{
Console.WriteLine("processing:" + i);
}

//make sure I am allowed to keep going
this.waitHandle.WaitOne();

//Can only run this once main thread is happy
for (int i = 0; i < 5; i++)
{
Console.WriteLine("last processing:" + i);
}
}
}
}

Hi,

OK cool, thanks for your reply and the informative code! Very useful!

A question though, how does the thread "pause" while it's waiting for
the autoresetevent? It it in a busy-wait loop or is the thread blocked?

I also take it from the way this line:

this.waitHandle.WaitOne();

is actually explicitly written into the worker at a certain point, that
you cant just pause a thread at any point?

In my current use of wanting to pause threads, there are no critical
sections etc. I simply have a UI where you adjust some settings then
press go. The second thread goes away and does some large calculation. I
only wanted to be able to pause the thread because the calculation takes
some serious power and using other apps in the meantime is a pain.
Indeed the calculation is a loop, so i could place:
this.waitHandle.WaitOne();
in it, but pressing pause wouldn't necessarily have immediate effect
(depending on which part of the loop it was at when pause was pressed)

In this case, is .suspend() actually dangerous?

Thanks

Andrew
Feb 19 '06 #7
Mark R. Dawson wrote:
Its always a good idea to try to know why you are not suppose to do
something, rather than just accepting a blanket statement, otherwise how do
you know when not to do it. Not looking into these things will lead to
comments like "Throwing Exceptions are expensive, don't ever throw them" or
"Never concatenate strings, always use a string builder" :-)

Mark.


Thanks for that little gem about strings ;)
Andrew
Feb 19 '06 #8
Hello Andrew,

The dangerous of Suspend is that it suspends the hardware thread, at whatever
position it is currently being executed.
If u suspend in the middle of the lock() {...} that lock won't be realized
till u resume the thread
Using event-based approach, as was recomended, u yourself put points where
thread could be suspended in the "safe" way.

Based on your description, why not to perform calculation based on the load
of CPU? Managed thread should check the load of CPU and raise priority of
calculating thread in case of idling, and reduce it if some apps is being
loaded

AB> In my current use of wanting to pause threads, there are no critical
AB> sections etc. I simply have a UI where you adjust some settings then
AB> press go. The second thread goes away and does some large
AB> calculation. I
AB> only wanted to be able to pause the thread because the calculation
AB> takes
AB> some serious power and using other apps in the meantime is a pain.
AB> Indeed the calculation is a loop, so i could place:
AB> this.waitHandle.WaitOne();
AB> in it, but pressing pause wouldn't necessarily have immediate effect
AB> (depending on which part of the loop it was at when pause was
AB> pressed)
AB> In this case, is .suspend() actually dangerous?
---
WBR,
Michael Nemtsev :: blog: http://spaces.msn.com/laflour

"At times one remains faithful to a cause only because its opponents do not
cease to be insipid." (c) Friedrich Nietzsche
Feb 19 '06 #9
Hi Andrew,
calling Wait on the WaitHandle puts the thread into the SleepWaitJoin
state, so it is not a busy-wait loop.

You are correct, using the wait handle will not have an immediate affect
on the thread, but only when it hits the line which asks if it is allowed to
proceed. I would suggest that maybe the background thread that you are using
to process is put on a lower than normal priority so that you are still able
to use other apps in the mean time. As you mention try to break the
processing down into discrete sections so that you are able to suspend at
minimal intervals.

Again, I would recommend against using Suspend in general, it is
considered bad practice, hence microsoft putting these methods as obsolete,
however if you know the ins and outs of your code then using it for simple
cases will not be dangerous but that is upto you.

Maybe others have different feeling on this?

Hope that helps
Mark Dawson
--
http://www.markdawson.org
"Andrew Bullock" wrote:
Mark R. Dawson wrote:
<snip>

private void ProcessValues()
{
//Can run this anytime
for (int i = 0; i < 5; i++)
{
Console.WriteLine("processing:" + i);
}

//make sure I am allowed to keep going
this.waitHandle.WaitOne();

//Can only run this once main thread is happy
for (int i = 0; i < 5; i++)
{
Console.WriteLine("last processing:" + i);
}
}
}
}

Hi,

OK cool, thanks for your reply and the informative code! Very useful!

A question though, how does the thread "pause" while it's waiting for
the autoresetevent? It it in a busy-wait loop or is the thread blocked?

I also take it from the way this line:

this.waitHandle.WaitOne();

is actually explicitly written into the worker at a certain point, that
you cant just pause a thread at any point?

In my current use of wanting to pause threads, there are no critical
sections etc. I simply have a UI where you adjust some settings then
press go. The second thread goes away and does some large calculation. I
only wanted to be able to pause the thread because the calculation takes
some serious power and using other apps in the meantime is a pain.
Indeed the calculation is a loop, so i could place:
this.waitHandle.WaitOne();
in it, but pressing pause wouldn't necessarily have immediate effect
(depending on which part of the loop it was at when pause was pressed)

In this case, is .suspend() actually dangerous?

Thanks

Andrew

Feb 19 '06 #10
Hi,

Thanks for everyones response :)

lots of knowledge gained ;)
Regards,

Andrew
Feb 19 '06 #11
Andrew Bullock <an*********************@ANDntlworldTHIS.com> wrote:

<snip>
Is there a newer (better) way I should be doing this, or am I OK to be
using these?


Others have suggested using ManualResetEvent. There's also
Monitor.Wait/Pulse, which is similar. It's less flexible than
ManualResetEvent, but I think it would be fine for what you're doing.
(It's a bit more efficient in .NET than ManualResetEvent, in my
experience, but that's unlikely to be an issue for you.)

See http://www.pobox.com/~skeet/csharp/t...eadlocks.shtml (half
way down the page) for more explanation and some sample code.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Feb 19 '06 #12

"Mark R. Dawson" <Ma*********@discussions.microsoft.com> wrote in message
news:40**********************************@microsof t.com...
Its always a good idea to try to know why you are not suppose to do
something, rather than just accepting a blanket statement, otherwise how
do
you know when not to do it. Not looking into these things will lead to
comments like "Throwing Exceptions are expensive, don't ever throw them"
or
"Never concatenate strings, always use a string builder" :-)


How about: "Because they are deprecated methods!"
Feb 20 '06 #13

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

Similar topics

1
by: Paul Tomlinson | last post by:
Quick question. If i call Thread.suspend() on a thread does the thread which is being suspended get any notification that it has been/is being suspended? I am thinking i want the...
4
by: am | last post by:
Hi to all. I have a little problem. I'm working with threads, and I need to abort or suspend them, but many experts dissuade from use Thread.Abort and Thread.Suspend. As I didn't find other way,...
6
by: Robert Speck | last post by:
Hi there, Can anyone shed anymore light on why "Thread.Suspend()" has been deprecated by MSFT beyond what MSDN says about it. I'm not sure if I quite appreciate the various pitfalls they discuss...
6
by: Buddy Home | last post by:
Hello, I want to understand whats the best way to write code to replace Thread.Suspend, Thread.Resume and Thread.Abort. I have lots of code calling these existing methods and want to minimize...
4
by: wanwan | last post by:
I'm using Microsoft Visual Studio 2005 in multithreading, I want to be able to pause and resume a thread. I see that suspend and resume are deprecated. So what can I use instead.
3
by: =?Utf-8?B?TWFyayBDaGFubmluZw==?= | last post by:
I have a code which registers all threads with a thread dump class. At intervals this thread dump class will dump the stack trace of all threads. As calling StackTrace(threadtoDump) from a...
1
by: Mike Fellows | last post by:
Having not used threads for such a long time in vb.net I have found myself in need of them I have a thread that runs and retirieves live data from a SQL database, this is running fine and has...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
isladogs
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...
1
isladogs
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...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
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
0
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...
0
isladogs
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...

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.