Using MbUnit 2.4, this test pass:
Guid g = Guid.Empty; Assert.AreEqual(Guid.Empty, g); Assert.AreNotEqual(Guid.Empty, g);
Using MbUnit 2.4, this test pass:
Guid g = Guid.Empty; Assert.AreEqual(Guid.Empty, g); Assert.AreNotEqual(Guid.Empty, g);
Given the following block of code:
if (presenter.GetServerUrlFromRequest!=null) GetServerUrlFromRequest.Checked = presenter.GetServerUrlFromRequest.Value; else GetServerUrlFromRequest.Checked = true;
Resharper gave me the following advice:
And turned the code to this piece:
GetServerUrlFromRequest.Checked = !(presenter.GetServerUrlFromRequest!=null) ||
presenter.GetServerUrlFromRequest.Value;
And while it has the same semantics, I actually had to dechiper the code to figure out what it was doing.
I choose to keep the old version.
I just tried to to do a major revamp of Rhino Mocks' interface. It was intended to make it easier to work with C# 3.0 and use the smarter compiler to get better syntax.
I shouldn't have bothered. Take a look at this.
public class TestCsc { public static void TestMethod() { Execute(Bar); // fail to compile Execute(delegate(int ia, string x) { }); // compiles fine Execute((int i, string x) => { return; }); // Compiles fine Execute((int i, string x) => { return true; }); // fail to compile Execute(Foo);// fail to compile Execute(delegate(int ia, string x) { return true; }); // fail to compile } public static bool Foo(int ia, string x) { return false; } public static void Bar(int ia, string x) { } public static void Execute<T, K>(Action<T, K> e) { } public static void Execute<T, K>(Func<bool, T, K> e) { } }
Annoyed.
I was playing around with the compiler when I hit this interesting feature. I was very surprised to see that this has compiled successfully.
1: static class Program2: {
3: static void Main(string[] args)4: {
5: IProcesser<GZipStream> p = null;6: p.HasTimeout();
7: }
8: }
9:
10: public static class Extensions11: {
12: public static bool HasTimeout<T>(this IProcesser<T> s)13: where T : Stream14: {
15: return s.Desitnation.CanTimeout;16: }
17: }
18:
19: public interface IProcesser<TDestination>20: where TDestination : Stream21: {
22: TDestination Desitnation { get; }
23: }
Greg Young posted about some issues that he run into with yield statements and compile time verifications in Spec#. He ends with:
Given this information are iterators something that are THAT desirable? Iterators are syntactical sugar, I can duplicate what an iterator does rather simply in code that does not use an iterator … Are they worth me giving up the possibility of removing all of my runtime checks or introducing this complexity?
My answer, yes, they are 100% desirable.
OO is syntactic sugar, there is enough object oriented C code out there to prove that, at least. But syntactic sugar matters, it matters because it allows you to reduce the complexity and move it to the compiler.
Take Rhino ETL as an example, the whole thing revolves around the idea of iterators. Making it any more complex than it has to will cause it to be infeasible.
The weight of the pattern or approach has direct correlation to its applicability. Dependency Injection doesn't work without an IoC container around, and iterators are far less useful if you don't have yield to make the pain go away.
A very common pattern for lazy initialization of expensive things is this:
GetDescriptionsHelper.Delegate getDescription; if (GetDescriptionsHelper.Cache.TryGetValue(entityType, out getDescription) == false) { MethodInfo getDescriptionInternalGeneric = getDescriptionInternalMethodInfo.MakeGenericMethod(entityType); getDescription = (GetDescriptionsHelper.Delegate)Delegate.CreateDelegate( typeof(GetDescriptionsHelper.Delegate), getDescriptionInternalGeneric); GetDescriptionsHelper.Cache.Add(entityType, getDescription); }
This tends to break down when we are talking about code that can run in multiply threads. So we start writing this:
lock(GetDescriptionsHelper.Cache) { GetDescriptionsHelper.Delegate getDescription; if (GetDescriptionsHelper.Cache.TryGetValue(entityType, out getDescription) == false) { MethodInfo getDescriptionInternalGeneric = getDescriptionInternalMethodInfo.MakeGenericMethod(entityType); getDescription = (GetDescriptionsHelper.Delegate)Delegate.CreateDelegate( typeof(GetDescriptionsHelper.Delegate), getDescriptionInternalGeneric); GetDescriptionsHelper.Cache.Add(entityType, getDescription); } }
Except, this is really bad for performance, because we always lock when we try to get the value out. So we start playing with it and get this:
GetDescriptionsHelper.Delegate getDescription; if (GetDescriptionsHelper.Cache.TryGetValue(entityType, out getDescription) == false) { lock(GetDescriptionsHelper.Cache) { MethodInfo getDescriptionInternalGeneric = getDescriptionInternalMethodInfo.MakeGenericMethod(entityType); getDescription = (GetDescriptionsHelper.Delegate)Delegate.CreateDelegate( typeof(GetDescriptionsHelper.Delegate), getDescriptionInternalGeneric); GetDescriptionsHelper.Cache.Add(entityType, getDescription); } }
This code has a serious error in it, in the right conditions, two threads will evaluate the if at the same time, and then try to enter the lock at the same time. The end result is an exception as the second of them will try to add the entity type again.
So we come out with the doubly checked lock, like this:
GetDescriptionsHelper.Delegate getDescription; if (GetDescriptionsHelper.Cache.TryGetValue(entityType, out getDescription) == false) { lock(GetDescriptionsHelper.Cache) { if (GetDescriptionsHelper.Cache.TryGetValue(entityType, out getDescription) ) return; MethodInfo getDescriptionInternalGeneric = getDescriptionInternalMethodInfo.MakeGenericMethod(entityType); getDescription = (GetDescriptionsHelper.Delegate)Delegate.CreateDelegate( typeof(GetDescriptionsHelper.Delegate), getDescriptionInternalGeneric); GetDescriptionsHelper.Cache.Add(entityType, getDescription); } }
Now we are handling this condition as well. But my preference of late has been to use this code in multi threaded environments.
Update: I should be wrong more often, I got some very good replies to this post. The code below happened to work by chance and luck alone, apparently. The solution above is the more correct one.
Actually, it is more complex than that. It is still possible to have readers attempt to read the Cache variable (which is of type Dictionary<Type, Delegate>) while it is being written to inside the lock. There is a potential for serious bit of mayhem in that case.
The safe thing to do in this case would be to lock it always before access, but for things that are going to be used frequently (hot spots) this can be a problem. Reader/Writer lock is much worse in terms or performance than the usual lock statement, and ReaderWriterLockSlim is for .NET 3.5 only.
An interesting dilemma, and I apologize for misleading you earlier.
GetDescriptionsHelper.Delegate getDescription; if (GetDescriptionsHelper.Cache.TryGetValue(entityType, out getDescription) == false) { MethodInfo getDescriptionInternalGeneric = getDescriptionInternalMethodInfo.MakeGenericMethod(entityType); getDescription = (GetDescriptionsHelper.Delegate)Delegate.CreateDelegate( typeof(GetDescriptionsHelper.Delegate), getDescriptionInternalGeneric); GetDescriptionsHelper.Cache[entityType] = getDescription; }
can you spot the main difference? We are not using locks, and we are using the indexer instead of the Add() method.
Empirical evidence suggest that using the indexer in a multi threaded environment is safe, in that it doesn't corrupt the dictionary and one of the values will remain there.
This means that assuming that the cost of creating the value isn't very high, it is just fine to have it created twice on those rare cases, the end result is after the initial flurry, we have the value cached, even if it was calculated more than once. In the long run, it doesn't matter.
Here is an interesting issue. Can you rely on System.Type.GUID to be stable?
By stable I mean that it will generate the same value for the same type across compilations. Empirical evidence suggest that this is the case, with the following factors determining the Guid of a type:
Reflectoring into the system, it turns out that System.Type.GUID is eventually translated to a call to System.RuntimeType.GetGUID, this is one of the scary InternallCall method that are implemented directly in the runtime itself.
I wonder...
One of the problems of multi threading is that there are a lot of intricacies that you have to deal with. Recently I run into issues that dictated that I would have to write an AsyncBulkInserterAppender for log4net.
One of the reasons that I want to do that is to avoid locking the application if the database is down or the logging table is locked.I just had a recent issue where this casued a problem.
When I implemented that, I started to worry about what would happen if the database is locked for a long duration. There is a chance that this async logging would block for a long time, and then another async batch would start, also blocking, etc. Eventually, it will fill the thread pool and halt the entire system.
This is the approach I ended up with, it should ensure that there is at most, only two threads that are writing to the database at a time. Since I wrote it, I already found at least two bugs in there. It looks fine now, but I can't think of any good way to really test that.
I am afraid that multi threading can't really be tested successfully. This is something where code review is required.
Here is the code:
protected override void SendBuffer(LoggingEvent[] events) { // we accept some additional complexity here // in favor of better concurrency. We don't want to // block all threads in the pool (train) if we have an issue with // the database. Therefor, we perform thread sync to ensure // that only a single thread will write to the DB at any given point ThreadPool.QueueUserWorkItem(delegate { lock (syncLock) { eventsList.AddLast(events); if (anotherThreadAlreadyHandlesLogging) return;
anotherThreadAlreadyHandlesLogging = true; } while (true) { LoggingEvent[] current; lock (syncLock) { if(eventsList.Count == 0) { anotherThreadAlreadyHandlesLogging = false; return; } current = eventsList.First.Value; eventsList.RemoveFirst(); } PerformWriteToDatabase(current); } }); }
Just a nod toward the people that cling to static typing with both hands, their teeth and the tail:
RouteTable.Routes.Add(new Route { Url = “admin/[controller]/[action]“, Defaults = new { Controller = “Admin“, Acton = “Index” }, Validation = new { Conrtoller = “Admin|Users|Categories” }, RouteHandler = typeof(MvcRouteHandler) });
Now, instead of abusing the language to get this, can we get first class support for this things?
No future posts left, oh my!