Oct 24, 2018

Éprouver en ligne C# compilateurs

Read this post in english

Leia este post em português

Salut

Je voulais remercier tout ceux qui m'ont aidé avec la correction de ce texte (sans ordre particulier): David Geoffroy, Charles Beauchemin, Jean-Philippe Leroux

Si vous travaillez avec C#, il est probable que, comme moi, vous finissiez par créer plusieurs projets seulement pour tester le comportement de certains extraits de code. Si c'est votre cas, je vous recommande d’utiliser un compilateur C# enligne, un site Web où vous pouvez taper un extrait de code C# et ce site compilera / exécutera le code. C’est un outil inestimable pour tester vos hypothèses sur le code très rapidement.

Entre autres, j’aime  sharplab.io, lequel, en plus de vous permettre jouer avec code C#, a aussi un ensemble de fonctionnalités intéressantes, que je vais décrire ci-dessous.

Sélection Branche / Fonctionnalité

Si vous suivez le développement du langage C# (ce que vous devriez faire), cette fonctionnalité est vraiment utile; cela vous permet de choisir quelle version du compilateur à utiliser (de plusieurs feature branches), ou entre autres, vous pouvez expérimenter diverses fonctionnalités en sélectionnant quel compilateur utiliser.

Afficher compilateur arbre de syntaxe (Syntax Trees)

Ceci ressemble à la fenêtre Roslyn Syntax Visualizer dans Visual Studio (vous avez besoin d'installer .NET Compiler Platform SDK dans Visual Studio pour que cette fenêtre devient disponible). Cette fonctionnalité est très utile pour tester la nouvelle syntaxe C#.

Afficher IL généré

C’est la sorte de fonctionnalité que la plupart des  développeurs C# n’ont jamais besoin, mais pour ceux qui en ont réellement besoin, elle est vraiment utile. Est-que vous voulez regarder comment un extrait de C# code est traduit pour IL? Simplement écrire le code et choisir IL dans le dropbox et voilà.

Afficher JITed/code ASM généré

Si la dernière fonctionnalité n’est pas pour plusieurs de développeurs C#, elle est encore plus limitée, mais elle peut vraiment aider les développeurs qui besoin de comprendre comment un extrait de C# code est traduit pour le langage machine (ASM).

Voilà!.

Amusez-vous bien!

Adriano

Oct 20, 2018

Avoiding hidden data copies in C#

Lire ce post en Francais

Leia este post em Português

Given the following code, Can you spot any issues? Hint: there's at least one, related to value types & performance!

Ok, lets make it a little bit more obvious by changing it to be a logical error instead of only a performance issue (the problem would be easly found if we had unit tests in place). Now what would be the expected output of the following code? 

If you answered:
M() : 0
M() : 1
M() : 2
you will be surprised to see:
M() : 0
M() : 0
M() : 0

and now it should be clear that something is not right.

The problem is that the field s has been declared as readonly which caused the compiler to make a defensive copy before each s.M() invocation (the compiler does not perform flow analysis to prove the invoked method will not violate the readonly invariant); this means that M() is increasing counter on a temporary value each time it is called leaving s.counter alone. 

Notice that in the first version of the code which don't rely on the struct to be mutable (which is good, since you should avoid mutable value types) it is not easy to realize something is not quite right. Even with the later version it is not clear why counter never gets incremented. 

To understand that lets look in at the IL for the Main() method (you can also use sharplab.io to play with the code) :
You can observe the copy happening at IL offsets IL_0001 (ldsfld valuetype S C::s) & IL_0006 (stloc.0) then again at offset IL_000f & IL_0014 and finally at offsets IL_001d & IL_0022. Notice that after copying s to the local variable at slot 0 (zero) the address of this local variable is loaded into the stack and  M() method is invoked.

Unfortunately C# language provide other opportunities to play tricks like this on us; I can think of at least 2 cases: in parameters and local ref readonly variables. See the example below:
So how can you avoid such hidden copies? The answer depends which version of C# you are targeting:
  • < 7.3: The only way to get rid of those copies (AFAIK) is to remove readonly modifier from the field (s in this example)
  • >= 7.3:  in this case you can declare your struct as readonly so the compiler will enforce this invariant (and emit an error if you try to mutate any of the struct's state).
One question that you may have now is: how bad are those  extra copy operations? IMO it depends on whether they affect your program performance (i) and/or behavior (ii) and your requirements. In the case that the behavior of the program is affected I think it is a consensus that those copies need to go whereas in the case in which performance is affected it is debatable whether one should invest time/effort to chase/fix those (of course, you always should have a performance goal). That being said, if you use Visual Studio for development you can install ErrorProne.NET which will pinpoint this type of issues.

Last but not least, if you are interested in deep content about .Net I recommend you to follow this blog

Adriano

Aug 17, 2018

A tale of incomplete documentation

Today I was investigating a potential implementation for one specific aspect of the application I am working on and that requires me to spawn a process which will create a file and the lifetime of the file needs to be tied to the lifetime of the owning process.

I could easily create the file when the process starts and delete it when the process is about to exit; the problem with this solution is that there are way too many things that can go wrong regarding deleting the file (for instance, if the process is terminated by Process.Kill() it is game over, i.e, it will not have a chance to delete the file).

Luckily there is a better alternative: to create the file with the option FileOptions.DeleteOnClose in which case the OS (Windows) guarantees that the file will be deleted when the last file handle is closed.

That is exactly what I need! The only problem is that the documentation of FileOptions enumeration is not clear about a very important detail: if you want to allow other process to be able to access that file you must specify FileShare.Delete (among other share modes you want to grant), otherwise any attempt to open the file will fail. Luckily the documentation for CreateFileW is more explicit about this:

Subsequent open requests for the file fail, unless the FILE_SHARE_DELETE share mode is specified. 

So I was able to figure that out (but not without a good amount of head scratching :( )

Hope this helps.

Adriano

Mar 28, 2018

Recursos para se manter atualizado com a linguagem C#

Read this post in English.

Olá

É surpreendente a quantidade de informações que temos a nossa disposição atualmente. Quando eu comecei a estudar programação (a alguns anos atrás :) ), informação sobre programação era muito limitada (morar em uma pequena cidade do interior de São Paulo e não ser capaz de ler nada em Inglês não ajudava muito).

A situação não melhorou muito quando entrei na universidade (3 ~ 4 anos após meu primeiro contato com um clone do Apple IIe); sem dúvida eu tinha acesso a mais livros, mas os mesmos eram em inglês (que eu ainda tinha muita dificuldade em ler por sinal) e também não cobriam uma ampla gama de assuntos da área.

Para nossa sorte (ou não), atualmente temos tanta informação disponível que temos dificuldade para acompanhar as novidades o que nos traz ao tema deste post: Neste mar de informações disponíveis temos que nos concentrar nas que podem nos proporcionar o melhor retorno pelo nosso investimo.

Se tratando da linguagem C#, para mim, do ponto de vista do desenvolvimento da mesma, todos desenvolvedor C# deveriam, pelo menos, conhecer o repositório https://github.com/dotnet/csharplang, o qual se auto denomina, o "repositório oficial para o design da linguagem C#"

Neste repositório você pode encontrar documentação relativa a funcionalidades existentes, e mais importante (em minha opinião), ainda em desenvolvimento (por exemplo, recentemente documentos referentes a algumas 
funcionalides da próxima versão da linguagem (7.3)  foram publicados). 

Lá você também encontra documentos sobre as várias reuniões de design da linguagem.(aqui você pode ver um vídeo, em inglês, descrevendo o processo de design e como você pode usar este repositório).

O mais interessante é que não estamos limitados a apenas consumir passivamente o conteúdo deste o repositório; como o mesmo é aberto qualquer um pode enviar sugestões de novas funcionalidades para a linguagem bem como participar de discussões sobre os vários recursos em desenvolvimento.

Happy coding ;)

Adriano

Keeping up with C# development

Leia este post em português

Hi

it is amazing how much information we have available nowadays. I remember when I started studding programming (some 30 years ago :) ), it was really hard to find information (ok, I used to live in a small city in Brazil and could not read English at all, but still, there were not a lot of information available about computers / programming). 

The situation did not improve much when I went to college (3 ~ 4 years after my first contact with an amazing Apple II clone); surely I had access to more books but unfortunately most of them were in English, and did not cover much ground (at least the ones I had available).

Luckily, nowadays we have plenty of information available (actually much more than what any single person can imagine consuming), which bring us to the topic of this post: As a C# developers we have some great resources at our disposal; from the language development perspective, in my opinion, every C# developer should, at least, be aware  of https://github.com/dotnet/csharplang, in their own words, the "official repo for C# language design"

In that repository you can find documentation about existing and, most interesting, 
under development, language features. As an example, recently design documents for the upcoming C# 7.3 version have been pushed). There we can also find documents for each of the Design Meetings which can be invaluable information for those interested in following the language evolution more closely (here you can find a video describing the design process and how that repo is used).

Notice that you are not limited to consuming information. Since that repository is open, anyone can participate and add his/her own suggestions.

To summarize, if you are interested in following the development of C#, you should definitely keep an eye on that.

Happy codding.

Adriano

Mar 22, 2018

Experimentando com código C# online

Read this post in english


Lire cet article en français

Olá

Se você trabalha com C# é provável que, assim como eu, você acabe criando vários projetos apenas para testar o comportamento de certos trechos de código. Se este é o seu  caso,  recomendo fortemente utilizar um Compilador C# Online, basicamente uma página na Web onde você pode digitar trechos de código C# e o mesmo será compilado / executado.

Dentre várias opções existentes, uma que me impressionou (e continua a impressionar) é o sharplab.io o qual possui várias funcionalidades (as quais descrevo brevemente abaixo) além do básico compilar/executar programas C# .

Seleção de versão do compilador a utilizar (baseado nas branches do github)

Se você acompanha o a evolução da linguagem C# este recurso é realmente útil já que o mesmo permite experimentar funcionalidades ainda em desenvolvimento simplesmente selecionando qual versão do compilador utilizar.

Visualizar / navegar na AST do código

Funcionalidade similar à janela Syntax Visualizer do Visual Studio (note que o .NET Compiler Platform SDK  deve estar instalado para esta janela ficar disponível no Visual Studio). Muito útil para entender um pouco mais sobre o Roslyn.

Mostrar o código IL

Acredito que esta funcionalidade não seja muito útil para a maioria dos desenvolvedores C# mas certamente a mesma é muito útil para uma parcela de desenvolvedores que lidam com IL no seu dia a dia. Além disso é uma ótima ferramenta para aprender um pouco mais sobre os detalhes de como .NET funciona. Altamente recomendado.



Visualizar o código assembly de métodos JITed

Se a funcionalidade anterior não é muito útil para uma ampla gama de desenvolvedores, o público alvo desta é ainda mais restrito (particularmente eu usei a mesma 1 ou 2 vezes). Quando esta opção é selecionada temos como resultado o código assembly gerado  pelo JIT o que nos permite estudar como o código C# é convertido para código de máquina.

Boa diversão ;)

Adriano

Mar 1, 2018

Online C# compilers

Leia esta post em Português

Lire cet article en français







Hi

If you develop using C# and you like to experiment with code you should try using one of the online C# compilers (there are a bunch of them). They allow you to quickly test assumptions about the C# code, test how code behaves, etc.

Among those, one that I grew to love is sharplab.io which besides allowing you to play with C# code, also has a set of really nice features, which I'll briefly describe bellow.

Branch/Feature selection

If you are following C# language development (you should ;)) this feature is really useful; it allows one to choose which compiler (built from various feature branches), to use, i.e, you can experiment with features under development by simply selecting which compiler to use.

Display compiler Syntax Trees

This is similar to  the Roslyn Syntax Visualizer window in Visual Studio (this window will only be available if you install .NET Compiler Platform SDK in Visual Studio). Very useful if you are playing with Roslyn.

Display Generated IL

This is the type of feature that most C# developers will never need, but for those who actually need, this is really powerful. Want to see how some piece of C# code is translated to IL? simply type the code and select IL in the dropbox and voialá. 

Show generated JITed/ASM code

If the previous feature was not for most C# developers, this one is even more restricted, but  it can really help developers that need to check how some piece of C# code is translated to actual machine code (this can be very useful when you are trying to better understand how your C# code runs in the processor)

That's it.

Have fun

Adriano