views:

58

answers:

2

Hi,

Does anyone know a way to get notified when a specific thread is being suspended and resumed?

I would like to be able to to something like this:

thread.Suspended += delegate
{
    //Do something
};

thread.Resumed += delegate
{
    //Do something else
};

I doubt that the .Net Framework has this capability, but is there a technique to achieve this maybe with pinvoke? I need it to be possible with low overhead.

A: 

Windows has no such notification mechanism for Thread.Suspend/Thread.Resume You should not be using Thread.Suspend/Thread.Resume - it can easily lead to deadlocks and other hard to find bugs. Use the normal synchronization primitives (locks, events, etc.) to cause a thread to block until it has work to do.

UPDATE:

You could enable context switch events in ETW and consume them via ProcessTrace. OldThreadId and OldThreadState will tell why a thread stopped running (transition to ready, standby, waiting, etc., etc.). NewThreadId will tell you when a thread starts running. You will have to process events for every context switch in the system. It will be incredibly high volume, consume a lot of CPU in your process, and be very difficult to get precisely right.

Michael
Thanks, but I'm not talking about using Thread.Suspend() or Thread.Resume(), I just want to get notified when a thread is suspended (by the scheduler or by a blocking operation). I wish there was a hack to be able to do this.
SelflessCoder
+2  A: 

If you're committed to writing your own thread pool this probably doesn't help, but I'd try to stick with the .NET ThreadPool class and tune it as required with SetMaxThreads/SetMinThreads and GetMaxThreads/GetAvailableThreads. Is there any particular reason why this isn't good enough?

I was at PDC last year and attended some of Joe Duffy's talks on parallelism were quite interesting. I recall he was talking about providing an extensible thread pool class in .NET since MSFT generally find that when people go and write their own thread pools they'll work fine most of the time, but get caught out in edge cases by various gotchas. By providing an extensibility mechanism they were hoping to limit the potential for devs to get caught out.

donovan
The .Net ThreadPool is good enough, it will add a thread to its pool only when a work item has been queued for more than one second. I was just experimenting for fun if it is possible for a thread pool to create new threads only when one of its thread has done a blocking operation, but I guess this is unmanageable.
SelflessCoder