Tag Archives: Programming in general

Coalescing operator with accessing object member access

Few days back Aleš Roubíček wrote an interesting article about, basically, needless code. You can read it here, though in Czech.

In one part he points to the coalescing operator ?? as being helpful while trying to write succinct code. And I agree. But also very often I need to not only coalesce the value itself, but, because we live with objects, also access some member on the object itself. Small example.

var d = DateTimeOrNull();
int? x;
if (d.HasValue)
  x = ((DateTime)d).Minute;
else
  x = null;

This pattern I find having in my code very often. But it’s hard to write it succinctly. Yes, I can use ternary operator ?:, but I still need to use intermediate variable. Boring. Having a language construct for this case would be interesting. Actually I wrote myself simple extension method for that, but that’s not the same as having it baked into the language.

I can imagine something like this (just shooting some syntax).

int? x = DateTimeOrNull() ? x => x.Minute ?? null;

Or am I only one thinking/bothering about this? :)

C# compiler (CSC) crash

Last week I was doing fairly simple change in a project I’m currently working on daily. Added a controller, model, few DTOs and orchestrated all this together using some methods from “library”. I had clean focus what to do and some pieces of new methods I already had in existing methods. So I partly also did small refactoring. While typing the code I noticed the red squiggles etc. are behaving weird already. When I was done with change I invoked build process and suddenly everything went wrong.

First

quickly followed by
.

Well, let’s try some basic healing steps. Restarting Visual Studio (2012); no luck. Deleting all bin, obj etc. and restarting Visual Studio; no luck either. OK, time to use big guns. Restarting complete machine; no luck.

Looking at the detailed build log I found (among tens of other errors below):

CSC : error CS0583: Internal Compiler Error (0xc0000005 at address 00FE7AFB): likely culprit is 'BIND'

Little bit search on internet didn’t brought anything helpful. So I decided to reproduce it. If it was working five minutes ago, it’s not going to be hard to pinpoint what caused it. So I created copy of project’s current state and reverted back. Then I started slowly adding pieces back and/or copying new files back. Surprisingly (and luckily) the problem went away.

Probably some bad coincidence, order of files, …, who knows. Thus if you face same or seemingly same error, try to redo your steps from working state. It’s probably going to work. And if not, report it, you have a reproducible test case, what’s better, isn’t it?

Do not overdo parallelism and asynchronous

Sometimes it’s easy to little bit overdo the need for having everything asynchronous and parallel. Quite often in last few weeks I’ve seen methods similar to this one.

Console.WriteLine("Starting");
Parallel.For(1, 10, async i =>
{
	await Task.Delay(200);
	Console.WriteLine(i);
});
Console.WriteLine("Finished");

What’s the result? For somebody maybe surprisingly:

Starting
Finished

Why? What we see here is a two pieces “process”. First the Parallel.For. This methods runs the provided method in parallel (for our discussion it doesn’t matter how and what exactly that means) and waits for all methods to complete. The lambda expression we’re providing is asynchronous. And though the async/await simplified the programming a lot, it’s still standing on basic principles around Tasks. And that’s the key for understanding what’s wrong. The async lambda is basically (I’m simplifying here) starting a task to do the work and returning that task so you can eventually (a)wait it to complete. But the Parallel.For care about the method (all of them) returning, not (a)waiting tasks (it’s actually an Action<int> also known as “async void” hence it has no idea about the task inside). And here you have it.

The question that’s left is, how to fix it? :) Probably easiest way is to extract the lambda to method and wait for that task to complete. That will make the method blocking so the Parallel.For is not going to end prematurely.

static void Main(string[] args)
{
	Console.WriteLine("Starting");
	Parallel.For(1, 10, i => Action(i).Wait());
	Console.WriteLine("Finished");
}

static async Task Action(int i)
{
	await Task.Delay(200);
	Console.WriteLine(i);
}

But wait. That’s a little bit crazy, isn’t it? We have tasks running asynchronously and we’re spinning Parallel.For and waiting??? You can actually run the loop starting the asynchronous methods capturing the returned tasks and then use Task.WaitAll or if you want to go really deep async ;) you can use Task.WhenAll and await it.

If you’d like to see something like ForEachAsync (or maybe ForAsync) you can get and inspiration and other interesting notes from this Stephen Toub’s blog post.

Easier ArgumentException messages

It’s a good practice to include parameter name when throwing ArgumentException (or similar). But I hate typing the parameter name as string. It’s A) boring and B) dumb, because when you refactor the parameter name you have to manually also change this string.

But why not let the language constructs help us? 8-) If we capture the parameter as expression we’ll be able to use static typing and extract the name from the expression node.

Shouldn’t be that hard, I thought one afternoon, and here’s the result (it really isn’t).

static string ArgumentExceptionMessage<T>(Expression<Func<T>> argument)
{
	var me = argument.Body as MemberExpression;
	if (me == null)
		throw new ArgumentException("Cannot extract argument name.", ArgumentExceptionMessage(() => argument));
	return me.Member.Name;
}

And you can use it (normally you would throw exception in all cases, I just wanted to show the result, hence Console.WriteLine).

class Foo
{
	public int MyProperty { get; set; }
}

static void Main(string[] args)
{
	var f = new Foo();
	Console.WriteLine(ArgumentExceptionMessage(() => args));
	Console.WriteLine(ArgumentExceptionMessage(() => f.MyProperty));

	throw new ArgumentException("This argument is not correct.", ArgumentExceptionMessage(() => args));
}

There’s never enough precondition checks. And understandable messages/parameters of exceptions is a valued help for developers. You can even wrap it to method returning ArgumentException directly to have more succinct code.

ID or Id?

Looks like there are two groups of developers. One writing ID and one writing Id. I'm in the first one, and I'm even not 100% sure why (except because my feelings are saying me, it's "more" correct). But it looks like there's no conclusion.

More and more I see the other option being used often (DbContext or HttpApplication to name a few), especially if you take into account properties like URL and so on. It even looks this is more common inside .NET Framework, but still, i.e. DBNull or System.Web.UI is an exception. Who knows...

Anyway, I'd like to ask you. What are your habits? Have you find some good pros (or cons) for one or the other? Or articles/papers/... about this naming? Share your thoughts in comments.

Update:
In "Framework Design Guidelines: Conventions, Idioms, and Patterns for Reusable .NET Libraries (2nd Edition)" I've found (link):

Two other terms that are in common usage are in a category by themselves, because they are common slang abbreviations. The two words Ok and Id (and they should be cased as shown) are the exceptions to the guideline that no abbreviations should be used in names.

Solved. On the other hand the DbContext and DBNull is still weird inconsistency.

Executing method in intervals – good and bad approaches

In last few days I’ve seen couple of pieces of code with “executing method every x seconds”. And a lot of bad. Not buggy, but superfluously expensive. I’m also here adding a simple loop to run just 10 times.

The first bad one is simply using Thread and Sleep method.

void BadOne1()
{
	Thread t = new Thread(o =>
		{
			for (int i = 0; i < 10; i++)
			{
				Console.WriteLine("BadOne1");
				Thread.Sleep(1000);
			}
		});
	t.Start(null);
}

Problem is the Thread object is very expensive and it’s used only fraction of time. The rest is blocked. Simply wasted resources.

I’ve also seen slightly better version.

void BadOne2()
{
	ThreadPool.QueueUserWorkItem(o =>
		{
			for (int i = 0; i < 10; i++)
			{
				Console.WriteLine("BadOne2");
				Thread.Sleep(1000);
			}
		});
}

This is really just a little bit better. ThreadPool thread is used, but again, the thread is doing nothing a lot of time. Again wasted resources.

Better approach is to use Timer. This way you’re not wasting resources by abusing threads. The callback from Timer is executed when the interval is elapsed (on ThreadPool thread). Rest of the time it’s just sits there waiting for next tick.

void GoodOne1()
{
	int i = 0;
	Timer t = null;
	t = new Timer(o =>
		{
			Console.WriteLine("GoodOne1");
			if (Interlocked.Increment(ref i) == 10)
			{
				// could tick, still
				t.Change(Timeout.InfiniteTimeSpan, Timeout.InfiniteTimeSpan);
				t.Dispose(); // or somewhere else
			}
		}, null, TimeSpan.Zero, TimeSpan.FromSeconds(1));
}

Here I’d like to point to my older post about keeping the reference to Timer.

And also one question that might come. The Timer ticks every interval no matter how long executing the callback took. That might not be what you want. You may want to execute the method with xx seconds delay between (previous examples), not execute the method every xx second (this example). The solution is pretty easy. Initially just schedule one tick and then reschedule it for next interval.

void GoodOne2()
{
	int i = 0;
	Timer t = null;
	t = new Timer(o =>
		{
			Console.WriteLine("GoodOne2");
			if (Interlocked.Increment(ref i) == 10)
			{
				// could tick, still
				t.Change(Timeout.InfiniteTimeSpan, Timeout.InfiniteTimeSpan);
				t.Dispose(); // or somewhere else
			}
			else
			{
				t.Change(TimeSpan.FromSeconds(1), Timeout.InfiniteTimeSpan);
			}
		}, null, TimeSpan.Zero, Timeout.InfiniteTimeSpan);
}

All these are kinda low level. But you can use Reactive Extensions (Rx) to write it in more succinct way, but internally the core idea is same as with Timer.

void GoodOne3()
{
	IDisposable obs = null;
	obs = Observable
		.Timer(TimeSpan.Zero, TimeSpan.FromSeconds(1))
		.Take(10)
		.Subscribe(_ =>
			{
				Console.WriteLine("GoodOne3");
			}, () => obs.Dispose() /* or somewhere else */);
}

No matter what approach you’ll use, please don’t (ab)use threads (manually created or ThreadPool ones). Threads are small little nice sweet creatures that don’t deserve to be treated like this. And. Don’t forget to cleanup resources (i.e. Timer is IDisposable).