views:

76

answers:

4

Hi

I have a thread that does the following:

1) Do some work
2) Wait
3) Do some more work
4) Wait
...

I want to (be able to) interrupt the thread while in one of the sleep sections but not in the work sections. The problem is that a work section might contain a smaller sleep section which might then catch an interrupt. So what I need is some way to prevent interrupt within a certain section, how can I do this?

A: 

In general you can't control when threads are scheduled, however Thread.Sleep forces a context switch and sounds like what you are after:

http://msdn.microsoft.com/en-us/library/d00bd51t.aspx

Kragen
A: 

Let the thread "interrupt" itself.

The most simple example I can think of is a BackgroundWorker and the use of the CancellationPending property. This is covered on MSDN and, while here relating to the BackgroundWorker in particular, is a concept that can easily be used elsewhere.

If larger definitions of "prevent interrupt" are needed, the use of additional "locks" (of various kinds, or rethinking design) are needed. In particular, with few exceptions, I am a firm believer that threads should have strong data-isolation and mutable objects should be owned by at most one thread.

pst
This could work. The threads are isolated and have a single owner, what I am trying to implement is cancelling a running task while at the same time ensuring that certain parts are completed before cancelling.
dphreak
+1  A: 

All you need is in "wait sections" wait for a single wait handle with a timeout period. Timeout period exceeding will mean here "continue".

Vitaliy Liptchinsky
A: 

Try to use some object to synchronize thread interrupting.

Object syncRoot;

In your thread, use lock statement for work sections:

lock (syncRoot)
{
    // Do someting here
}

When you need to interrupt your thread, also do this inside lock statement:

lock (syncRoot)
{
    // Interrupt your thred here
}
SMART_n
This could work, but it would require a mutex object for each thread, but this does seem quite simple.
dphreak