Uninterruptable section
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 wor开发者_如何转开发k 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?
All you need is in "wait sections" wait for a single wait handle with a timeout period. Timeout period exceeding will mean here "continue".
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
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.
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
}
精彩评论