473,785 Members | 2,354 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 31955
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
1655
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
11108
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
10271
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
3199
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
6058
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
4082
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
9484
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10350
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8983
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...
1
7505
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
6742
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
5386
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
5518
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4055
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
3
2887
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.