I have a situation where for testing, I want my timer method (FooMethod) to run one at a time. In the example below, FooMethod is passed as a delegate to a timer. There are many specific examples of this class. I thought that by setting _locker static, only one instance of FooMethod () would process at a time. But when I run the application, several threads go through the TryEnter () line at a time.
This is how I add each class to the new timer. This is done in a loop for each instance of foo:
_timers.Add(new Timer(foo.FooMethod, null, 0, 10000));
And this is the class that has this method:
public class Foo<T> { private static readonly object _locker = new object(); public void FooMethod(object stateInfo) {
Note. As a rule, _locker is not static; I do not want the same thread to introduce a method before it gets a chance to complete. I changed it to statics here for testing.
My first thought is that maybe this is not working because the class is generic? And that each particular class is actually its own class, and they do not share the _locker variable? It's true? If this is true, how should I have specific classes sharing the _locker variable? Do I need to add the _locker static variable to some other class that Foos have access to?
Bob horn
source share