1) I'm working on a project and I saw this piece of code, I don't understand what is the point of the Monitor.Lock statement. Can someone explain what its trying to do?
2) the postscript underscroll in the parameter name is really annoying, anyone else seen this naming convention?
public class FieldsChangeableHelper<T> : IFieldsChangeable<T>
{
object _lock;
int _lockCount;
FieldChanges<T> _changes;
public FieldsChangeableHelper()
{
_lock = new object();
_lockCount = 0;
}
public void AddChange(T field_, object oldValue_)
{
if (_changes == null)
_changes = new FieldChanges<T>(field_, oldValue_);
else
_changes.AddChange(field_, oldValue_);
if (RaiseEvent(_changes))
_changes = null;
}
#region IFieldsChangeable Members
public void BeginUpdate()
{
if (System.Threading.Interlocked.Increment(ref _lockCount) == 1)
Monitor.Enter(_lock);
}
public void EndUpdate()
{
if (System.Threading.Interlocked.Decrement(ref _lockCount) == 0)
{
FieldChanges<T> changes = _changes;
_changes = null;
Monitor.Exit(_lock);
RaiseEvent(changes);
}
}
protected bool RaiseEvent(FieldChanges<T> changes_)
{
if (_lockCount == 0 && Changed != null && changes_ != null)
{
Changed(this, changes_);
return true;
}
return false;
}
public event FieldsChanged<T> Changed;
#endregion
}
Monitor.Lock locks the portion of code when multiple thread tries to execute the same piece in parallel. It is made to ensure that only 1 guy is altering/executing the context. Look at the MSDN.
Although its best practice that the locking object is always static, but in your case it is not. Which might pose some problem if your instantiating multiple objects on an open type.
Note one thing, in generics static on open T is different for different type, i.e static member in an Open Type class in your case is different for T i.e DateTime, string, etc.
In csharp, private members of a type are usually named with prefixed _
The way i read it: BeginUpdate() ensures that the current thread calling has exclusive access to the instance and that change events practically will be batched and raised once EndUpdate is called. The author wanted to deal with recursion by itself (e.g. calling BeginUpdate() on the same thread multiple times) and a mechanism to batch UpdateEvents untill after the lock has been released. Because, there is a potential deadlock when raising Events when you still have a lock on yourself. event subscribers might want to access your members and therefore have to lock the sender instance which is already locked.
The whole conditional locking is not required (if my analyses is correct ofcourse) since locks based on the Monitor class are recursive and counted.
There is another problem with the locking mechanism, that is: currently when one thread holds a lock. The second thread wont even wait for the lock but will simply continue without a lock since the lock is conditional! this seems like a big bug!
Regarding the naming convention. I use it myself for a way of differentiating privates from parameters and locals. Its a preference which many C# coding conventions recommend. This helps in a case like this:
void Method(int number)
{
// no need to refer to this since:
//this.number = number;
// can be replaced with
_number = number;
}
Related
I have understood that lock() locks a region of lines of code, other threads cannot access the locked line(s) of code. EDIT: this turns out to be just wrong.
Is it also possible to do that per instance of an object? EDIT: yes, that's is just the difference between static and non-static.
E.g. a null reference is checked during a lazy load, but in fact there is no need to lock other objects of the same type?
object LockObject = new object();
List<Car> cars;
public void Method()
{
if (cars == null)
{
cars = Lookup(..)
foreach (car in cars.ToList())
{
if (car.IsBroken())
{
lock(LockObject)
{
cars.Remove(car)
}
}
}
}
return cars;
}
EDIT, would this be a correct way to write this code:
Because when cars == null and thread A locks it, then another thread B will wait. Then when A is ready, B continues, but should check again whether cars == null, otherwise the code will execute again.
But this looks unnatural, I never saw such a pattern.
Note that locking the first null-check would mean that you acquire a lock even to check for null and every time again and again .. so that is not good.
public void Method()
{
if (cars == null)
{
lock(LockObject)
{
if (cars == null)
{
cars = Lookup(..)
foreach (car in cars.ToList())
{
if (car.IsBroken())
{
cars.Remove(car)
}
}
}
}
}
return cars;
}
It's important to realise that locking is very much a matter of the object locked on.
Most often we want to lock particular blocks of code entirely. As such we use a readonly field to lock a section and hence prevent any other running of that code either at all (if the field is static) or for the given instance (if the field is not static). However, that is a matter of the most common use, not the only possible use.
Consider:
ConcurrentDictionary<string, List<int>> idLists = SomeMethodOrSomething();
List<int> idList;
if (idLists.TryGetValue(someKey, out idList))
{
lock(idList)
{
if (!idList.Contains(someID))
idList.Add(someID);
}
}
Here "locked" section can be called simultaneously by as many threads as you can get going. It cannot, however, be called simultaneously on the same list. Such a usage is unusual, and one has to be sure that nothing else can try to lock on one of the lists (easy if nothing else can access idLists or access any of the lists either before or after they are added into it, hard otherwise), but it does come up in real code.
But the important thing here is that obtaining the idList is itself threadsafe. When it came to creating a new idList this more narrowly-focused locking would not work.
Instead we'd have to do one of two things:
The simplest is just lock on a readonly field before any operation (the more normal approach)
The other is to use GetOrAdd:
List<int> idList = idLists.GetOrAdd(someKey, () => new List<int>());
lock(idList)
{
if (!idList.Contains(someID))
idList.Add(someID);
}
Now an interesting thing to note here is that GetOrAdd() doesn't guarantee that if it calls the factory () => new List<int>() that the result of that factor is what will be returned. Nor does it promise to call it only once. Once we move away from the sort of code that just locks on a readonly field the potential races get more complicated and more thought has to go into them (in this case the likely thought would be that if a race means more than one list is created, but only one is ever used and the rest get GC'd then that's fine).
To bring this back to your case. While the above shows that it's possible to lock not just as finely as your first example does, but much more finely again, the safety of it depends on the wider context.
Your first example is broken:
cars = Lookup(..)
foreach (car in cars.ToList()) // May be different cars to that returned from Lookup. Is that OK?
{
if (car.IsBroken()) // May not be in cars. Is that OK?
{ // IsBroken() may now return false. Is that OK?
lock(LockObject)
When the ToList() is called it may not be calling it on the same instance that was put into cars. This is not necessarily a bug, but it very likely is. To leave it you have to prove that the race is safe.
Each time a new car is obtained, again cars may have been over-written in the meantime. Each time we enter the lock the state of car may have changed so that IsBroken() will return false in the meantime.
It's possible for all of this to be fine, but showing that they are fine is complicated.
Well, it tends to be complicated when it is fine, sometimes complicated when it's not fine, but most often it's very simple to get the answer, "no, it is not okay". And in fact that is the case here, because of one last point of non-thread-safety that is also present in your second example:
if (cars == null)
{
lock(LockObject)
{
if (cars == null)
{
cars = Lookup(..)
foreach (car in cars.ToList())
{
if (car.IsBroken())
{
cars.Remove(car)
}
}
}
}
}
return cars; // Not thread-safe.
Consider, thread 1 examines cars and finds it null. Then it obtains a lock, checks that cars is still null (good), and if it is it sets it to a list it obtained from Lookup and starts removing "broken" cars.
Now, at this point thread 2 examines cars and finds it not-null. So it returns cars to the caller.
Now what happens?
Thread 2 can find "broken" cars in the list, because they haven't been remove yet.
Thread 2 can skip past cars because the list's contents are being moved by Remove() around while it is working on it.
Thread 2 can have the enumerator used by a foreach throw an exception because List<T>.Enumerator throws if you change the list while enumerating and the other thread is doing that.
Thread 2 can have an exception thrown that List<T> should never throw because Thread 1 is half-way in the middle of one of its methods and its invariants only hold before and after each method call.
Thread 2 can obtain a bizarre franken-car because it read part of a car before a Remove() and part after it. (Only if the the type of Car is a value-type; reads and writes of references is always individually atomic).
All of this is obviously bad. The problem is that you are setting cars before it is in a state that is safe for other threads to look at. Instead you should do one of the following:
if (cars == null)
{
lock(LockObject)
{
if (cars == null)
{
cars = Lookup(..).RemoveAll(car => car.IsBroken());
}
}
}
return cars;
This doesn't set anything in cars until after the work on it has been done. As such another thread can't see it until it's safe to do so.
Alternatively:
if (cars == null)
{
var tempCars = Lookup(..).RemoveAll(car => car.IsBroken());
lock(LockObject)
{
if (cars == null)
{
cars = tempCars;
}
}
}
return cars;
This hold the lock for less time, but at the cost of potentially doing wasteful work just to throw it away. If it's safe to do this at all (it might not be) then there's a trade-off between potential extra time on the first few look-ups for less time in the lock. It's some times worth it, but generally not.
The best strategy to perform lazy initializing is by using properties for fields:
private List<Car> Cars
{
get
{
lock (lockObject)
{
return cars ?? (cars = Lockup(..));
}
}
}
Using your lock object here also makes sure, that no other thread also creates an instance of it.
Add and remove operations have also to be performed while locked:
void Add(Car car)
{
lock(lockObject) Cars.Add(car);
}
void Remove(Car car)
{
lock(lockObject) Cars.Remove(car);
}
Recognize the use of the Cars property to access the list!
Now you can get a copy of your list:
List<Car> copyOfCars;
lock(lockObject) copyOfCars = Cars.ToList();
Then it is possible to safely remove certain objects from the original list:
foreach (car in copyOfCars)
{
if (car.IsBroken())
{
Remove(car);
}
}
But be sure to use your own Remove(car) method which is locked inside.
Especially for List there is another possibility to cleanup elements inside:
lock(lockObject) Cars.RemoveAll(car => car.IsBroken());
There are situations where I'm quite fond of static events, but the fact that I rarely see them in other people's code makes me wonder if I'm missing something important. I found a lot of discussions about static events on this site, but most of them deal with situations that I'm not interested in (like on static classes) or where I wouldn't think of using them in the first place.
What I am interested in are situations where I might have many instances of something and a single instance of a long-living "manager" object that reacts to something on those instances. A very simple example to illustrate what I mean:
public class God {
//the list of followers is really big and changes all the time,
//it seems like a waste of time to
//register/unregister events for each and every one...
readonly List<Believer> Believers = new List<Believer>();
God() {
//...so instead let's have a static event and listen to that
Believer.Prayed += this.Believer_Prayed;
}
void Believer_Prayed(Believer believer, string prayer) {
//whatever
}
}
public class Believer {
public static event Action<Believer, string> Prayed;
void Pray() {
if (Prayed != null) {
Prayed(this, "can i have stuff, please");
}
}
}
To me, this looks like a much cleaner and simpler solution than having an instance event and I don't have to monitor changes in the believers collection either. In cases where the Believer class can "see" the God-type class, I might sometimes use a NotifyGodOfPrayer()-method instead (which was the preferred answer in a few similar questions), but often the Believer-type class is in a "Models"-assembly where I can't or don't want to access the God class directly.
Are there any actual downsides to this approach?
Edit: Thanks to everyone who has already taken the time to answer.
My example may be bad, so I would like to clarify my question:
If I use this kind of static events in situations, where
I'm sure there will only ever be one instance of the subscriber-object
that is guaranteed to exist as long as the application is running
and the number of instances I'm watching is huge
then are there potential problems with this approach that I'm not aware of?
Unless the answer to that question is "yes", I'm not really looking for alternative implementations, though I really appreciate everyone trying to be helpful.
I'm not looking for the most pretty solution (I'd have to give that prize to my own version simply for being short and easy to read and maintain :)
One important thing to know about events is that they cause objects which are hooked to an event not to be garbage collected until event owner is garbage collected, or until event handler is unhooked.
To put it into your example, if you had a polytheistic pantheon with many gods, where you promoted and demoted gods such as
new God("Svarog");
new God("Svantevit");
new God("Perun");
gods would remain in your RAM while they are attached to Believer.Prayed. This would cause your application to leak gods.
I'll comment on design decision also, but I understand that example you made is maybe not best copy of your real scenario.
It seems more reasonable to me not to create dependency from God to Believer, and to use events. Good approach would be to create an event aggregator which would stand between believers and gods. For example:
public interface IPrayerAggregator
{
void Pray(Believer believer, string prayer);
void RegisterGod(God god);
}
// god does
prayerAggregator.RegisterGod(this);
// believer does
prayerAggregator.Pray(this, "For the victory!");
Upon Pray method being called, event aggregator calls appropriate method of God class in turn. To manage references and avoid memory leaks, you could create UnregisterGod method or hold gods in collection of weak references such as
public class Priest : IPrayerAggregator
{
private List<WeakReference> _gods;
public void Pray(Believer believer, string prayer)
{
foreach (WeakReference godRef in _gods) {
God god = godRef.Target as God;
if (god != null)
god.SomeonePrayed(believer, prayer);
else
_gods.Remove(godRef);
}
}
public void RegisterGod(God god)
{
_gods.Add(new WeakReference(god, false));
}
}
Quick tip: Temporarily store event delegate as listeners might unhook their event handlers
void Pray() {
var handler = Prayed;
if (handler != null) {
handler(this, "can i have stuff, please");
}
}
Edit
Having in mind details you added about your scenario (huge number of event invokers, constant and single event watcher) I think you chose right scenario, purely for efficiency reasons. It creates least memory and cpu overhead. I wouldn't take this approach generally, but for scenario you described static event is very pragmatic solution that I might take.
One downside I see is flow of control. If your event listener is created in single instance as you say, then I would leverage singleton (anti)pattern and invoke method of God from Believer directly.
God.Instance.Pray(this, "For the victory!");
//or
godInstance.Pray(this, "For the victory!");
Why? Because then you get more granular control over performing action of praying. If you decide down the line that you need to subclass Believer to a special kind that doesn't pray on certain days, then you would have control over this.
I actually think that having an instance even would be cleaner and defiantly more readable.
It is much more simple to view it as, an instance is preying, so his pray event gets trigger. And I don't see ant downsides for that. I don't think that monitor changes is not more of a hustle than monitoring the static event. but is the correct way to go...
Monitoring the list:
Change the list to be an ObservableCollection (and take a look at NotifyCollectionChangedEventArgs ).
Monitor it by:
public class God {
readonly ObservableCollection<Believer> Believers = new ObservableCollection<Believer>();
public God() {
Believers = new ObservableCollection<T>();
Believers.CollectionChanged += BelieversListChanged;
}
private void BelieversListChanged(object sender, NotifyCollectionChangedEventArgs args) {
if ((e.Action == NotifyCollectionChangedAction.Remove || e.Action == NotifyCollectionChangedAction.Replace) && e.OldItems != null)
{
foreach (var oldItem in e.OldItems)
{
var bel= (Believer)e.oldItem;
bel.Prayed -= Believer_Prayed;
}
}
if((e.Action==NotifyCollectionChangedAction.Add || e.Action==NotifyCollectionChangedAction.Replace) && e.NewItems!=null)
{
foreach(var newItem in e.NewItems)
{
foreach (var oldItem in e.OldItems)
{
var bel= (Believer)e.newItem;
bel.Prayed += Believer_Prayed;
}
}
}
}
void Believer_Prayed(Believer believer, string prayer) {
//whatever
}
}
I'm using a switch as a state manager for my XNA game. The switch is a part of main update method, so it's run every frame. Sometimes I need to set a timer value and it should only be set once per method call. There are multiple methods that set the timer per case, so it can't use the current and previous state numbers to check if it's ok to overwrite previous time.
case "state 34": {
SetTime(theTime); // should run only once
// other things
if (TheTimeisRight(time)) // runs every call
{
SetTime(theTime); // should run only once
if (TheTimeisRight(time))
{ /* some methods */ }
}
break; }
How can I make this work, or is there a better way to do this without going outside the switch? (changing SetTime method is ok, but I wouldn't like to clutter up the switch with additional code)
Another method: Introduce a wrapper around the method you want to call:
public sealed class RunOnceAction
{
private readonly Action F;
private bool hasRun;
public RunOnceAction(Action f)
{
F = f;
}
public void run()
{
if (hasRun) return;
F();
hasRun = true;
}
}
Then create var setTimeOnce = new RunOnceAction(() => SetTime(theTime)); before the switch statement, and call there as setTimeOnce.run(). Adjust for parameters/return values as necessary.
If you don't want to mess with boolean variables ala hasSetTimeAlready, you can always introduce another state that calls the method, then proceeds to the original state.
Put the call outside the loop.
You might need a separate conditional statement to determine whether it should run at all, but that's got to be infinitely better than trying to use flags and/or various other smelly-code approaches to control repetitions of the call.
Edit:
here is what I mean by putting it in one place outside of the switch:
if (someCondition && someOtherCondition && yetAnotherCondition)
setTime(theTime); // just one call, in one place, gets executed once
switch(someValue)
{
case "state 34": {
//SetTime(theTime); // no longer necessary
// other things
if (TheTimeisRight(time)) // runs every call
{
//SetTime(theTime); // no longer necessary
if (TheTimeisRight(time))
{ /* some methods */ }
}
break;
...etc...
}
A word of advice: use an enumeration for your switch value rather than a string.
To be brutally honest, this is about as much as anyone can realistically help you with this without seeing a more complete code sample (I think the sample you gave us is somewhat contrived and not quite accurate to what you have?). Chances are that the best way to get round this problem is to deconstruct the switch statement and start again because either maintaining a state machine is not the best way to handle this situation or you need to introduce some other states.
I have resorted to using HashSet<int> to check if the current SetTime(time, num) method has not been called before with if (!hashSet.Contains(num)).
void SetTime(int time, int num)
{
if (!hashSet.Contains(num))
{
theTime = time;
hashSet.Add(num);
}
}
Sure doesn't look too cool, but works and it doesn't damage method call too much (visually), so the switch's readability is saved.
For an assignment (it's for concurrency if you wonder) - I have to implement my own lock
(more specific: a TaS, a TTas and an Array-Lock, as described in "The Art of Multiprocessor Programming")
There are some test in- and output schemes online that I tried (too bad they take pretty long to try).
Your program is to count 9-digit numbers that pass a certain test
(it's called the elfproef in dutch, I don't know the english equivalence, sorry).
Sometimes I got a slightly different number, which suggests that my lock doesn't work a 100% right.
I have implemented the locks like this:
interface Lock
{
void Lock();
void Unlock();
}
class TaSLock : Lock
{
AtomicBool state = new AtomicBool(false);
void Lock.Lock()
{ while (state.getAndSet(true)); }
void Lock.Unlock()
{ state.getAndSet(false); }
}
The AtomicBool is implemented with an integer, because the Interlocked class doesn't have operations for Boolean variables. This isn't optimal in terms of memory usage but it doesn't (or shouldn't) matter for the speed.
class AtomicBool
{
int value;
static int True = 1, False = -1;
public AtomicBool(bool value)
{
if (value) this.value = True;
else this.value = False;
}
public void set(bool newValue)
{
if (newValue) Interlocked.Exchange(ref value, True);
else Interlocked.Exchange(ref value, False);
}
public bool getAndSet(bool newValue)
{
int oldValue;
if (newValue) oldValue = Interlocked.Exchange(ref value, True);
else oldValue = Interlocked.Exchange(ref value, False);
return (oldValue == True);
}
public bool get()
{
return (Interlocked.Add(ref value, 0) == 1);
}
}
Now in the parallel part I have just used:
theLock.Lock();
counter++;
theLock.Unlock();
But each time I get slightly different results.
Is there something obvious I'm doing wrong?
Hans is right. Your atomic get-and-set boolean appears to be correct -- in fact, it appears to me to be somewhat over-engineered. And the lock appears to be correct as well, insofar as you've built yourself a potentially highly inefficient "spin lock". (That is, all the waiting threads just sit there in a tight loop asking "can I go yet? can I go yet?" instead of going to sleep until it is their turn.)
What is not correct is that your lock provides no guarantee whatsoever that any two threads that both have a view of "counter" have a consistent view of "counter". Two threads could be on different processors, and those different processors could have different copies of "counter" in their caches. The cached copies will be updated, and only occasionally written back to main memory, thereby effectively "losing" some increases.
The real implementation of locking in C# ensures that a full-fence memory barrier is imposed so that reads and writes cannot move "forwards and backwards in time" across the fence. That gives a hint to the processors that they need to not be so smart about caching "counter" so aggressively.
I'm sure I've seen this around before but I'm wondering how I should raise an event thread-safely.
I have a message despatch thread which looks somthing like.
while(_messages > 0){
Message msg;
// get next message
if (MessageDispatched != null)
MessageDispatched(this, new MessageDispatchedEventArgs(msg.Msg, msg.Params));
}
I can see that it may be posible for MessageDispatched to be come null after the check. from a MS blog I've seen:
var handler = MessageDispatched;
if (handler != null)
handler(this, new MessageDispatchedEventArgs(msg.Msg, msg.Params));
Which does stop the possibility of the reference becoming null after the check occurring. I'm wondering how to handle the case where the delegate is disposed (or even if it can?)
Should I just need to stick a try / catch around it, as its probably very rarely going to occur?
Edit
After reading answers I've considered making my class to handle this - quickly it looks something whats below, but I'm running into a few issues which make it not as clean as I want - maybe someone has an idea how to do that?
public class ThreadSafeEvent<TDelegate>
// where TDelegate : Delegate why is this a non allowed special case???
{
List<TDelegate> _delegates = new List<TDelegate>();
public void Subscribe(TDelegate #delegate)
{
lock (_delegates)
{
if (!_delegates.Contains(#delegate))
_delegates.Add(#delegate);
}
}
public void Unsubscibe(TDelegate #delegate)
{
lock (_delegates)
{
_delegates.Remove(#delegate);
}
}
// How to get signature from delegate?
public void Raise(params object[] _params)
{
lock (_delegates)
{
foreach (TDelegate wrappedDel in _delegates)
{
var del = wrappedDel as Delegate;
del.Method.Invoke (del.Target, _params);
}
}
}
}
The latter structure will make sure you won't get a null reference exception calling the handler on non-Itanium architectures.
However, it leads to another possible issue -- it's possible for a client that registered an event handler to have the handler called after it's been removed. The only way to prevent that is to serialize raising the event and registering the handler. However, if you do that, you have a potential deadlock situation.
In short, there are three potential classes of ways this can break -- I go with the way you've done it here (and MS recommends) and accept that it is possible for an event handler to get called after it is unregistered.
Please, check this out: Checking for null before event dispatching… thread safe?
Read this post from Eric Lippert : Events and Races