473,701 Members | 2,760 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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(myC lass.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 31927
On Sun, 19 Feb 2006 15:08:57 GMT, Andrew Bullock
<an************ *********@ANDnt lworldTHIS.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 ManualResetEven t
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.Collecti ons.Generic;
using System.Text;
using System.Threadin g;

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

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

//let main UI thread so some processing
Console.WriteLi ne("Main thread working");
Thread.Sleep(50 00);

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

Console.ReadLin e();
}
}

class Worker
{
private WaitHandle waitHandle;

public void DoSomeWork(Wait Handle waitHandle)
{
this.waitHandle = waitHandle;

Thread t = new Thread(new ThreadStart(Pro cessValues));
t.Start();
}

private void ProcessValues()
{
//Can run this anytime
for (int i = 0; i < 5; i++)
{
Console.WriteLi ne("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.WriteLi ne("last processing:" + i);
}
}
}
}
using System;
using System.Collecti ons.Generic;
using System.Text;
using System.Threadin g;

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

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

//let main UI thread so some processing
Console.WriteLi ne("Main thread working");
Thread.Sleep(50 00);

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

Console.ReadLin e();
}
}

class Worker
{
private WaitHandle waitHandle;

public void DoSomeWork(Wait Handle waitHandle)
{
this.waitHandle = waitHandle;

Thread t = new Thread(new ThreadStart(Pro cessValues));
t.Start();
}

private void ProcessValues()
{
//Can run this anytime
for (int i = 0; i < 5; i++)
{
Console.WriteLi ne("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.WriteLi ne("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(myC lass.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************ *********@ANDnt lworldTHIS.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 ManualResetEven t 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(myC lass.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.co m> wrote:
Using Suspend is not good idea, use ManualResetEven t 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.WriteLi ne("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.WriteLi ne("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.WriteLi ne("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.WriteLi ne("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

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

Similar topics

1
1654
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 thread-to-be-suspended to log the fact that it is being suspended. Any ideas?
4
11107
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, how can I do? Thanks a lot!
6
1418
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 but using it under certain circumstances still seems reasonable. For instance, I want to display a small modal dialog with a "Cancel" button which allows the user to abort a background thread. If the user clicks this button, I then want to prompt...
6
10269
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 the risk of changing the code everywhere so here is what I think I could do, which is to create my own ThreadWrapper class which inherits from Thread and which has these three methods already defined but does it a different way and then my...
4
3194
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
6050
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 different thread other than the treadToDump the threadToDump must be suspended otherwise a ThreadStateException gets thrown. However under .NET 2.0 System.Threading.Thread.Suspend/Resume have been marked as obsolete with reference to better methods of...
1
4074
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 been doing its job for a long time the problem is I need to suspend this thread when a checkbox is clicked (as the data is no longer required) but when the checkbox is unclicked it needs to restart
0
9084
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
8978
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
8936
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...
0
7827
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5905
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
4411
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
4665
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3104
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2399
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.