Tag Archives: C#

Tasks – try on retrying, loops, recursions

My mind today was in weird shape (again). I blame Friday. What that means is, that I came with weird pieces of code, that are fun to just write. Brain training. :)

The set up was simple. I had a Task that was returning bool; true if succeeded, false otherwise. Because the code was interacting with 3rd party system it was desired to retry if the call didn’t succeeded.

Looking at it in front of me I realized I’ll be probably able to (ab)use the ContinueWith method and recursion. When I wrote it I realized there’s a room for refactoring. And then I realized I might create and extension method from it. Already half way in hell. :)

public static Task<TResult> Retry<TResult>(this Func<Task<TResult>> taskMethod, Func<TResult, bool> resultOK, int retries)
{
	return taskMethod()
		.ContinueWith(t =>
			retries == 0 || resultOK(t.Result)
				? Task.FromResult(t.Result)
				: Retry(taskMethod, resultOK, --retries))
		.Unwrap();
}

Umm, how it will look like with await, I thought. Then I can use loop.

public static async Task<TResult> Retry2<TResult>(this Func<Task<TResult>> taskMethod, Func<TResult, bool> resultOK, int retries)
{
	while (true)
	{
		var result = await taskMethod();
		if (retries-- == 0 || resultOK(result))
			return result;
	}
}

This doesn’t look nice. I thought it will be smoother. This is like 90s. Back to recursion.

public static async Task<TResult> Retry3<TResult>(this Func<Task<TResult>> taskMethod, Func<TResult, bool> resultOK, int retries)
{
	var result = await taskMethod();
	return retries == 0 || resultOK(result)
		? result
		: await Retry3(taskMethod, resultOK, --retries);
}

That looks better. I don’t know whether I like the first or the third version more. But. What about performance? The second version has least code to execute. No doubt. The third version has two awaits and the recursion (nesting) with awaits. This is probably not going to be good for performance. And my tests confirms that. Slightly slower than second is the first version. Thus the winner for me is version #1. 8-)

I’m not sure why I did this (from practical perspective), but it was fun. Have a great Friday.

String splitting and ordering enlightenment

Couple of years back I wrote a C# that was splitting response from server to lines. I had the data as one string and I needed to have it as array of strings, based on lines. Pretty simple, right?

The code I wrote was basically this.

response.Split(new[] { "\r", "\n", "\r\n" }, StringSplitOptions.None);

And it was working fine. Until yesterday. The server part of the solution was moved to new machine and new language. And now it started returning the exact same string, except for new lines. Now the line endings were \r\n, standard on Windows. Without too much thinking you immediately realize, the code above still works, but splits “too much”.

Of course, the fix was easy, just changing the order, having \r\n first.

Silly me. Still learning.

TaskCanceledException on timeout on HttpClient

.NET Framework has a nice new class for all sort of HTTP stuff called HttpClient (interesting the name wasn’t taken before :) ). And because it’s I/O related it has also bunch on XxxAsync methods to nicely fit into C# 5′s async/await.

So you might write code similar to this, based on experience based on previous “network” classes.

var client = new HttpClient();
client.Timeout = TimeSpan.FromMilliseconds(200); //adjust based on your network
try
{
	var result = await client.GetStringAsync("http://blog.cincura.net/");
}
catch (HttpRequestException)
{
	// handle somehow
	Console.WriteLine("HttpRequestException");
}
catch (TimeoutException)
{
	// handle somehow
	Console.WriteLine("TimeoutException");
}

If you try to run it, you’ll get unhandled exception, TaskCanceledException to be precise. Yep, the timeout is not propagated as TimeoutException, but as TaskCanceledException. It caught me off guard a little bit. The documentation for Timeout property touches CancellationTokenSource and you can feel the steer to TaskCanceledException. But, still, could be mentioned explicitly, will not be that surprising. Or maybe my thinking was skewed.

This code then works correctly.

var client = new HttpClient();
client.Timeout = TimeSpan.FromMilliseconds(200);
try
{
	var result = await client.GetStringAsync("http://blog.cincura.net/");
}
catch (HttpRequestException)
{
	// handle somehow
	Console.WriteLine("HttpRequestException");
}
//catch (TimeoutException)
//{
//	// handle somehow
//	Console.WriteLine("TimeoutException");
//}
catch (TaskCanceledException)
{
	// handle somehow
	Console.WriteLine("TaskCanceledException");
}

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.