Tagged: design patterns

Creating futures

Futures (and promises) are a fun and useful design pattern in that they help encapsulate asynchronous work into composable objects. That and they help hide away the actual asynchronous execution implementation. It doesn’t matter if the future is finally resolved on the threadpool, in a new thread, or in an event loop (like nodejs).

Asynchronous work wrapped in futures has garnered a lot of attention in the javascript world since they alleviate the heavy use of nested callbacks to return a final result. But futures aren’t limited to just javascript, the C# async keyword is a form of a future, Java has a futures class, and a lot of other languages have the ability to use futures.

In order to to demystify the concept of Futures lets build own version. Futures aren’t hard to implement, even when you have a language that doesn’t have them built in (or if you … Read more

Command pattern with SignalR

I’m using SignalR as a long poll mechanism between multiple .NET clients because part of my projects requirements is to have everything over http/https. There’s no point in rolling my own socket based long poll since SignalR has already done all the heavy lifting. Unfortunately since the app I work on is distributed I can’t upgrade my SignalR version from what I have (0.5.2) since the newer SignalR versions aren’t backwards compatabile. This means I have to make do with what this version of SignalR gives me.

Still, the version I have works great for my purposes and I can’t complain. However, I was getting frustrated at having to constantly update my internal boilerplate whenever I wanted to add a new hub method dispatch. What I want is to have a single method dispatch and encapsulate all my business logic in a command pattern so that I never have to … Read more

Async producer/consumer the easy way

This article was originally published at tech.blinemedical.com

In .net 4, a new class called BlockingCollection was introduced, which let you have a threadsafe producer/consumer queue. Anyone consuming a BlockingCollection blocks automatically until new items are added. This lets you easily add items to the collection in one thread and use another synchronized thread to consume items. This class is great since before this existed, you had to do all this work with mutexes and it was a lot of extra work (and more error prone). In general, a good time to use a decoupled producer consumer pattern is when you have a slow consuming function and a producer thread that is time sensitive.

Even though BlockingCollection effectively synchronizes your producer/consumer, you still have to create boilerplate to manage the producer thread and the consumer thread. Also if you wanted to add extra exception handling or a cancellation token, you’d have … Read more