Inline assembly in C#

I was working on trying to figure out how sqeeze out some more speed for some calculations, which involved the following bit of math. SumOfSquares=i=0Ndatai2 The language of choice was C# with Visual Studio 2013 for a 64-bit process. One idea was to try and use SSE to improve the throughput of the computation. Unfortunately the .NET framework currently (as of .NET 4.2) does not generate SSE instructions as part of its JIT compiler. A workaround would be to make a dll with the math function exported, and call that exported function from C# using PInvoke. The Visual Studio compiler (2012 and above) is an excellant optimizing compiler with the ability to auto-vectorize loops. But then I would have to add a C dll as a dependency of my C# application. One more file to keep track just for a single calculation. ...

October 1, 2015 · 16 min · 3326 words · Bilal Durrani

Async-await and WaitHandles

The TPL is great but sometimes you have to work within a framework which schedules background tasks for you without giving you access to a Task of some kind. I had a situation like the following 1 2 3 4 5 6 7 8 private void DoSomeWork(CancellationToken token) { token.ThrowIfCancellationRequested(); // do lots of work } // some other code that might happen in a UI thread AsyncWorkScheduler.Schedule(()=> DoSomeWork(token)); I didn’t really have access to how the background task was scheduled, and to be honest I didn’t really care. What I needed was a way to wait for the work to finish, whether it finished by itself or if it was cancelled via the CancellationToken. I wanted to use await to avoid blocking any UI threads as well. ...

July 7, 2015 · 3 min · 441 words · Bilal Durrani

Prefetch data from disk

The task was simple. I have data on disk where the file sizes varied from 1kb to a couple of gigs. I needed to process the data and return the points from a method that returns an IEnumerable. The specific data file has a custom format, so I had to use a custom API to read the data. There was no async I/O option available unfortunately. Sounds simple enough. Here is my first version. I replaced the custom API with a simple file read operation. As with the custom API, I read pairs of data in block sizes I can specify. ...

July 1, 2015 · 4 min · 850 words · Bilal Durrani