AsyncLock

A naive implementation of async lock

https://github.com/ebalynn/AsyncLock

Behind the scenes the implementation uses SemaphoreSlim to do all the heavy lifting which already has a support for async/await.

You would normally use AsyncLock within a “using” statement. To keep the implementation as simple as possible I do not use any cancellation tokens for any of the operations.

Usage:

private readonly AsyncLock _lock = new AsyncLock();
public async Task DoSomethingAsync()
{
  using (await _lock.EnterAsync())
  {
    await Task.Delay(TimeSpan.FromSeconds(1));
  }
}

Simples

Retrieving state in a FirstChanceException in .NET — Network Programming in .NET

If you’re using a application-wide FirstChanceException handler, this is great for covering lots of bases at once, it helps make sure that you can catch (and record) an exception even if it happens with a bit of code you didn’t expect. However, the scope of the handler is what it is, so accessing state, and […]

Retrieving state in a FirstChanceException in .NET — Network Programming in .NET

Free e-book: Blazor for ASP.NET Web Forms Developers — ASP.NET Blog

We are thrilled to announce the release of our new e-book: Blazor for ASP.NET Web Forms developers. This book caters specifically to ASP.NET Web Forms developers looking for guidelines. As well as strategies for migrating their existing apps to a modern, open-source, and cross-platform web framework. Blazor E-book for ASP.NET Web Forms Blazor is a…

Free e-book: Blazor for ASP.NET Web Forms Developers — ASP.NET Blog

The Most Easy to Use ViewModeBase

This is something I wrote for an application I’m developing. This is an implementation of INotifyPropertyChanged that requires no backing fields, just call Set(value) or Get(). Internally it uses a dictionary to store the state and even reuses ChangedEventArgs

The source code can be found at:

https://github.com/ebalynn/StatefulViewModel/

Here is the extract from the ViewModel class that does all the heavy lifting:

Continue reading “The Most Easy to Use ViewModeBase”

C# Regrets: Top Worst C# Features

Stumbled upon this article written by no other than Eric Lippert listing the top 10 design faults of C# language. Here is the summary,  the source to the full article is at the bottom. 

#10: The empty statement does nothing for me

Reflects on the fact that lone “;” is a legal statement

#9: Too much equality

There are too many ways check for equality: ==, Equals, ReferenceEquals, CompareTo(…).

From personal experience double.NaN == double.NaN is false but double.NaN.Equals(double.NaN) is true

#8: That operator is shifty

Weirdness around << and >> operators

#7: I’m a proud member of lambda lambda lambda

The way C# 2.0 implements anonymous delegates

#6: Bit twiddling entails parentheses

Flags Enums

#5: Type first, ask questions later

C# borrows the “type first” pattern from C and many of its other successor languages – something I got used to and the “correct” way now seems illogical to me

#4: Flag me down

The fact that you can create invalid enum values and have to manually check for this in the code

#3: I rate plus-plus a minus-minus

++i, i++, i +=1 etc. how much confusion and the pain it caused.

#2 I want to destruct finalizers

Agree with the author that finilisers in C# are symptoms of a bug. Seen it way too many times myself.

#1 You can’t put a tiger in the goldfish tank, but you can try

“array covariance” and how this could lead to run-time exceptions.

Source: http://www.informit.com/articles/article.aspx?p=2425867

AForge.Net

Definitely something to play with when my brain has more oxygen (suffering from anaemia right now)

Deneme 1 2 3!

AForge.NET  is a C# framework designed for developers and researchers in the fields of Computer Vision and Artificial Intelligence – image processing, neural networks, genetic algorithms, machine learning, robotics, etc.

  • AForge.Imaging – library with image processing routines and filters;
  • AForge.Vision – computer vision library;
  • AForge.Neuro – neural networks computation library;
  • AForge.Genetic – evolution programming library;
  • AForge.Fuzzy – fuzzy computations library;
  • AForge.MachineLearning – machine learning library;
  • AForge.Robotics – library providing support of some robotics kits;
  • AForge.Video – set of libraries for video processing
  • etc.

are mainly topic in this framework. İf you want more information and help  visit: https://code.google.com/p/aforge/

View original post

Cache Consideration in Multi-Threaded Code

In parallel programs is very important to regard cache size and hit rates on a single CPU, but it’s even more important to consider how the caches of multiple processors/cores interact. Let’s consider a single representative example, which demonstrates the important cache optimisation and emphasizes the value of good tools when it comes to performance optimisation in general.

Let’s first examine the first sequential method, it performs the rudimentary task of summing all the elements in a two-dimensional array of integers and returns the result:

public static int MatrixSumSequential(int [,] matrix)
{
    int sum = 0;
    int rows = matrix.GetUpperBound(0);
    int cols = matrix.GetUpperBound(1);
    for(int i = 0; i < rows; i++)
    {
        for(int j = 0; j < cols; j++)
        {
            sum += matrix[i, j];
        }
    }
    return sum;  
}

We could have used TPL but let’s ignore the huge arsenal of tools TPL provides in our simple example. The following attempt at parallelisation may appear sufficiently reasonable to harvest the fruits of multi-core execution, and even implements a crude aggregation to avoid synchronisation on the shared sum variable:

public static int MatrixSumParallel(int [,] matrix)
{
    int sum = 0;
    int rows = matrix.GetUpperBound(0);
    int cols = matrix.GetUpperBound(1);
    const int THREADS = 4;
    int chunk = row / THREADS;
    int [] localSums = new int[THREADS];
    Threads [] threads = new Threads[THREADS];
    for(int i = = 0; i < THREADS; i++)
    {
        int start = chunk * i;
        int end - chunk * (1 + i);
        int threadNum = i;
        threads[i] = new Thread(() => {
            for(int row = start; row < end; r++)
            {
                for(int col = 0; col < cols; col++)
                {
                    localSums[threadNum] += matrix[row, col];
                }
            }
        });
        threads[i].Start();
        foreach(var thread in threads)
            thread.Join();
    }
    return localSums.Sum();
}

 

Executing each of the two methods several times on an i7 machine with 6 cores produced the following results for a 2,000 x 2,000 matrix of integers:

  • 325ms average for sequential method
  • 935ms for the parallel method. Three times as slow as the sequential method!

The obvious question is why?
This is not an example of too fine grained parallelism because the number of threads is only 4. However if you accept the premise that the problem is somehow the cache related, it would make sense to measure the number of cache misses introduced by the 2 methods above.

The Visual Studio profiler when sampling the execution of each method with a 2,000 x 2,000 matrix reported 963 exclusive samples in the parallel version and only 659 exclusive samples in the sequential version, the vast majority of samples being on the inner loop line that reads from the matrix.

Why would a line of code writing to localSums introduce so many cache misses in comparison to writing to sum local variable? The answer is that the writes to the shared array invalidate cache lines at other processors/cores, causing every += operating to be a cache miss.
When the processor writes to a memory location that is in the cache of another processor/core cache, the hardware causes a cache invalidation, that marks the cache line as invalid. Accessing that line results in a cache miss.

The moral of the story do not blindly introduce parallelization in a hope that that would also result in the performance increase. Always test both versions, you might be surprised at the results!

Fraction Implementation in C#

I’m not really sure why Microsoft have never bothere with implementing a Fraction primitive in .NET. I’m sure there are plenty of uses as fraction allow to preserve the maximum possible precision. I have therefore decided to create my own implementation (albeit somewhat primitive at this stage) .

My implementation automatically simplifies the fraction, so if you we to create new Function(6, 3) that would be simplified to 2. The Fraction struct implements all the arithmetic operators on itself and on Int64, float, double and decimal.

Internally the Fraction is represented as two Int64: Numerator and Denominator and is always simplified upon initialisation. I initially intended to have it as an option, however following profiling the cost of simplification is not that great and the benefits outweigh the performance drawbacks. 

Fraction has explicit conversion to Int64 (although that is bound to lose precision), float, double and decimal. It supports comparison with Int64, float, double and decimal and even supports ++ and — operations.

So far I have provided more or less complete implementation with plenty of Unit Test. Now the hard word of optimising the performance begins!

Design of Fractions

Fraction is implemented as a struct (pretty obvious choice). It takes a numerator as the first argument and denominator,  it then tries to simplify the fraction using the Euclidean algorithm, so if you were to specify 333/111 it would become 3.

The implementation supports all arithmetic operations with long, float, double and decimal and can also be converted to those type by either calling the corresponding methods or using explicit cast.

You can also create a function from either a long, float, double or decimal. Conversion from a long is quite trivial however conversion from a float, double or a decimal goes through a while loop and multiplies the floating point number until it has no decimal places. This method is relatively slow and therefore is not recommended.

Apart from that the Fraction behaves like a fist class citizen: you can compare a Fraction to any other number, divide, multiply, add, subtract, compare, increment decrement etc.

For example:

var oneThird = Fraction(1, 3);
var reciprocal = oneThird.Reciprocal();

Console.WriteLine(oneThird * reciprocal) : "1"
Console.WriteLine(++oneThird) : "4/3" - just like with an integer ++ adds 1 
Console.WriteLine(oneThird * oneThird) : "1/9"

 

Please feel free to contribute to the codebase if you feel like it

https://github.com/ebalynn/Balynn.Maths.Fraction

Blog at WordPress.com.

Up ↑