Pull to refresh
153
0
Stanislav Sidristij @sidristij

Семинары по платформе .NET CLRium

Send message

The architecture of an exceptional situation: pt.2 of 4

Reading time13 min
Views1.3K

I guess one of the most important issues in this topic is building an exception handling architecture in your application. This is interesting for many reasons. And the main reason, I think, is an apparent simplicity, which you don’t always know what to do with. All the basic constructs such as IEnumerable, IDisposable, IObservable, etc. have this property and use it everywhere. On the one hand, their simplicity tempts to use these constructs in different situations. On the other hand, they are full of traps which you might not get out. It is possible that looking at the amount of information we will cover you’ve got a question: what is so special about exceptional situations?


However, to make conclusions about building the architecture of exception classes we should learn some details about their classification. Because before building a system of types that would be clear for the user of code, a programmer should determine when to choose the type of error and when to catch or skip exceptions. So, let’s classify the exceptional situations (not the types of exceptions) based on various features.

Read more →
Total votes 10: ↑9 and ↓1+8
Comments0

Exceptional situations: part 1 of 4

Reading time11 min
Views2.1K


Introduction


It’s time to talk about exceptions or, rather, exceptional situations. Before we start, let’s look at the definition. What is an exceptional situation?


This is a situation that makes the execution of current or subsequent code incorrect. I mean different from how it was designed or intended. Such a situation compromises the integrity of an application or its part, e.g. an object. It brings the application into an extraordinary or exceptional state.


But why do we need to define this terminology? Because it will keep us in some boundaries. If we don’t follow the terminology, we can get too far from a designed concept which may result in many ambiguous situations. Let’s see some practical examples:


 struct Number
 {
     public static Number Parse(string source)
     {
         // ...
         if(!parsed)
         {
             throw new ParsingException();
         }
         // ...
     }

     public static bool TryParse(string source, out Number result)
     {
        // ..
        return parsed;
     }
 }

This example seems a little strange, and it is for a reason. I made this code slightly artificial to show the importance of problems appearing in it. First, let’s look at the Parse method. Why should it throw an exception?

Read more →
Total votes 27: ↑26 and ↓1+25
Comments2

Оптимизация программ под Garbage Collector

Reading time5 min
Views12K

Не так давно на Хабре появилась прекрасная статья Оптимизация сборки мусора в высоконагруженном .NET сервисе. Эта статья очень интересна тем, что авторы, вооружившись теорией сделали ранее невозможное: оптимизировали свое приложение, используя знания о работе GC. И если ранее мы не имели ни малейшего понятия, как этот самый GC работает, то теперь он нам представлен на блюдечке стараниями Конрада Кокоса в его книге Pro .NET Memory Management. Какие выводы почерпнул для себя я? Давайте составим список проблемных областей и подумаем, как их можно решить.


На недавно прошедшем семинаре CLRium #5: Garbage Collector мы проговорили про GC весь день. Однако, один доклад я решил опубликовать с текстовой расшифровкой. Это доклад про выводы относительно оптимизации приложений.


Total votes 40: ↑40 and ↓0+40
Comments4

Disposable pattern (Disposable Design Principle) pt.3

Reading time15 min
Views3.9K


Multithreading


Now let’s talk about thin ice. In the previous sections about IDisposable we touched one very important concept that underlies not only the design principles of Disposable types but any type in general. This is the object’s integrity concept. It means that at any given moment of time an object is in a strictly determined state and any action with this object turns its state into one of the variants that were pre-determined while designing a type of this object. In other words, no action with the object should turn it into an undefined state. This results in a problem with the types designed in the above examples. They are not thread-safe. There is a chance the public methods of these types will be called when the destruction of an object is in progress. Let’s solve this problem and decide whether we should solve it at all.


This chapter was translated from Russian jointly by author and by professional translators. You can help us with translation from Russian or English into any other language, primarily into Chinese or German.

Also, if you want thank us, the best way you can do that is to give us a star on github or to fork repository github/sidristij/dotnetbook.
Read more →
Total votes 12: ↑11 and ↓1+10
Comments0

CLRium #5 Garbage Collector: Питер — Sold Out

Reading time2 min
Views1.9K

13 апреля в Санкт-Петербурге (оффлайн и онлайн) и 20 апреля — в Москве (только оффлайн) пройдет самый крупный семинар CLRium#5 за всё время его существования.


Прокопав дебри алгоритмов управления памятью я теперь могу, наконец, ответить на извечный вопрос: "а зачем это знать?". Раньше кроме как just for fun до этого момета мне сложно было что-то ответить по одной простой причине: по-хорошему мы ничего не знали о том, как работает память в .NET. Мы знали что есть GC, что есть в целях оптимизации три поколения. Кто-то из нас даже знал про эфимерные сегменты и карточный стол. Но это выглядело скорее как буклет к чему-то более сложному, что никак не описано. И теперь, когда есть и исходники и люди, в них копающиеся, мы, наконец можем ответить на этот вопрос.


Мы приглашаем вас всех на этот семинар и в течении которого с 10:00 до 20:00 с перерывами на снять напряжение с головы будет рассказано очень и очень многое о том, как же всё-таки всё устроено.


Читать дальше →
Total votes 24: ↑22 and ↓2+20
Comments4

Memory and Span pt.3

Reading time10 min
Views2.5K


Memory<T> and ReadOnlyMemory<T>


There are two visual differences between Memory<T> and Span<T>. The first one is that Memory<T> type doesn’t contain ref modifier in the header of the type. In other words, the Memory<T> type can be allocated both on the stack while being either a local variable, or a method parameter, or its returned value and on the heap, referencing some data in memory from there. However, this small difference creates a huge distinction in the behavior and capabilities of Memory<T> compared to Span<T>. Unlike Span<T> that is an instrument for some methods to use some data buffer, the Memory<T> type is designed to store information about the buffer, but not to handle it. Thus, there is the difference in API.


  • Memory<T> doesn’t have methods to access the data that it is responsible for. Instead, it has the Span property and the Slice method that return an instance of the Span type.
  • Additionally, Memory<T> contains the Pin() method used for scenarios when a stored buffer data should be passed to unsafe code. If this method is called when memory is allocated in .NET, the buffer will be pinned and will not move when GC is active. This method will return an instance of the MemoryHandle structure, which encapsulates GCHandle to indicate a segment of a lifetime and to pin array buffer in memory.

This chapter was translated from Russian jointly by author and by professional translators. You can help us with translation from Russian or English into any other language, primarily into Chinese or German.

Also, if you want thank us, the best way you can do that is to give us a star on github or to fork repository github/sidristij/dotnetbook.
Read more →
Total votes 9: ↑9 and ↓0+9
Comments0

Disposable ref structs в C# 8.0

Reading time4 min
Views17K

Давайте посмотрим, что об этом сказано в блоге о предстоящих изменениях в С# 8.0 (версия Visual Studio 2019 Preview 2):


«stack-only структуры появились в С# 7.2. Они чрезвычайно полезны, но при этом их использование тесно связано с ограничениями, например невозможностью реализовывать интерфейсы. Теперь ссылочные структуры можно очищать с помощью метода Dispose внутри них без использования интерфейса IDisposable».


Так и есть: stack-only ref структуры не реализуют интерфейсы, иначе возникала бы вероятность их упаковки. Следовательно, они не могут реализовывать IDisposable, и мы не можем использовать эти структуры в операторе using:


class Program
{
   static void Main(string[] args)
   {
      using (var book = new Book())
      {
         Console.WriteLine("Hello World!");
      }
   }
}

ref struct Book : IDisposable
{
   public void Dispose()
   {
   }
}

Попытка запустить этот код приведёт к ошибке компиляции

Читать дальше →
Total votes 29: ↑28 and ↓1+27
Comments42

Memory and Span pt.2

Reading time9 min
Views3.2K


Span<T> usage examples


A human by nature cannot fully understand the purpose of a certain instrument until he or she gets some experience. So, let’s turn to some examples.


ValueStringBuilder


One of the most interesting examples in respect to algorithms is the ValueStringBuilder type. However, it is buried deep inside mscorlib and marked with the internal modifier as many other very interesting data types. This means we would not find this remarkable instrument for optimization if we haven’t researched the mscorlib source code.


What is the main disadvantage of the StringBuilder system type? Its main drawback is the type and its basis — it is a reference type and is based on char[], i.e. a character array. At least, this means two things: we use the heap (though not much) anyway and increase the chances to miss the CPU cash.


Another issue with StringBuilder that I faced is the construction of small strings, that is when the resulting string must be short e.g. less than 100 characters. Short formatting raises issues on performance.


This chapter was translated from Russian jointly by author and by professional translators. You can help us with translation from Russian or English into any other language, primarily into Chinese or German.

Also, if you want thank us, the best way you can do that is to give us a star on github or to fork repository github/sidristij/dotnetbook.
Read more →
Total votes 12: ↑11 and ↓1+10
Comments0

CLRium #5: Garbage Collector. Крупнейший семинар по .NET

Reading time2 min
Views4.1K

Наш семинар уверенно набирает слушателей и постепенно перерастает офис компании EPAM в Петербурге: мы планируем набрать до 250 разработчиков под одной крышей как в Петербурге, так и в Москве. А всё почему?


Когда-то я выступал с докладом по работе Garbage Collector и доклад этот хоть и был длиной в 45 минут, он покрывал все известные на тот момент темы. Вы наверняка его видели: ведь он был и на CLRium #2 и на конференции .NEXT, где являлся кей-ноутом. Докладом, открывающим конференцию (огромное спасибо 23derevo и real_ales за возможность). Кроме моего и многих других докладов в свет вышла книга Under the Hood of .NET Memory Management, проливающая свет на алгоритмы работы подкапотного пространства платформы .NET. И примерно в тот период времени, когда к движку CLR так вырос интерес, на собеседованиях начали появляться вопросы про этот самый GC. Не поверхностные вопросы, а с некоторым уклоном в "расскажите поподробнее". И хоть такие вопросы и вызывали бурю возмущения у специалистов, те люди, которые рассказывали о ядре подробно, были без проблем устроены на работу. Зачастую, с хорошим повышением оклада.


Сегодня у вас есть по сути два пути, чтобы стать приоритетом #1 для работодателя:


  1. Найти месяц-два времени и прочитать книгу Pro .NET Memory Management
  2. Сходить на наш семинар и за один день понять вообще всё. Плюс получить видеозаписи для того чтобы потом освежить память


CLRium #5: Garbage Collector пройдет 13 апреля в Санкт-Петербурге и 20 апреля — в Москве, а все подробности — под катом

Читать дальше →
Total votes 29: ↑29 and ↓0+29
Comments3

Disposable pattern (Disposable Design Principle) pt.2

Reading time8 min
Views2.9K


SafeHandle / CriticalHandle / SafeBuffer / derived types


I feel I’m going to open the Pandora’s box for you. Let’s talk about special types: SafeHandle, CriticalHandle and their derived types.


This is the last thing about the pattern of a type that gives access to an unmanaged resource. But first, let’s list everything we usually get from unmanaged world:


The first and obvious thing is handles. This may be an meaningless word for a .NET developer, but it is a very important component of the operating system world. A handle is a 32- or 64-bit number by nature. It designates an opened session of interaction with an operating system. For example, when you open a file you get a handle from the WinApi function. Then you can work with it and do Seek, Read or Write operations. Or, you may open a socket for network access. Again an operating system will pass you a handle. In .NET handles are stored as IntPtr type;


This chapter was translated from Russian jointly by author and by professional translators. You can help us with translation from Russian or English into any other language, primarily into Chinese or German.

Also, if you want thank us, the best way you can do that is to give us a star on github or to fork repository github/sidristij/dotnetbook.
Read more →
Total votes 24: ↑23 and ↓1+22
Comments0

Как глубока кроличья нора? CLRium #5: Garbage Collector

Reading time2 min
Views5.2K

Мир несется вперед, движимый прогрессом и конкуренцией. Нам с вами нереально повезло: ведь для нас работают величайшие умы, создавая поистине серъезные механизмы: компиляторы, IDE, базы данных. Делают их так, что мы получаем истинное удовольствие, используя их.


Один из этих механизмов — это работа подсистемы управления памятью платформы .NET. И если раньше никто не имел ни малейшего понятия как оно работает, то теперь, когда у нас есть исходники, все секреты открыты. Теперь видно абсолютно все подробности работы ядра платформы: и это действительно завораживает. Например, если ранее мы думали, что выделение памяти — это просто сдвинуть указатель, то теперь стало ясно что все несколько сложнее и интереснее. Это выверенный, прекрасный алгоритм, не оставляющий вопросов: а почему сделано именно так.


Второй очень важный момент — полное отсутствие времени между работой и семьей чтобы всё выучить и понять: разобраться с аспектами работы платформы. Так вот данный семинар — прекрасная возможность не тратя десятки часов на вычитку блогов и книг раз и навсегда разобраться, как же всё функционирует. И поверьте, я очень постараюсь чтобы каждый момент был ясен всем



CLRium #5: Garbage Collector пройдет 13 и 14 апреля в Санкт-Петербурге и 20 апреля — в Москве, а все подробности — под катом

Читать дальше →
Total votes 25: ↑24 and ↓1+23
Comments4

Не надо думать о памяти, говорили они… Семинар CLRium #5: Garbage Collector

Reading time1 min
Views5.1K
13 и 14 апреля в Санкт-Петербурге, а 20 апреля в Москве будет проведен семинар CLRium #5, целиком и полностью посвященный подсистемам ядра CoreCLR и .NET Framework.

Это тот редкий случай, когда знания без всякой воды будут вливаться вам в голову на протяжении всего дня. Когда вы на собесах станете знать гораздо больше собеседующих. Ведь эта информация раскидана по всему интернету, а рассказана будет лишь единожды.

10 докладов. Исключительно про ядро. 6 из них — только про подсистему управления памятью.


Читать дальше →
Total votes 24: ↑23 and ↓1+22
Comments2

Disposable pattern (Disposable Design Principle) pt.1

Reading time9 min
Views3.3K


Disposable pattern (Disposable Design Principle)


I guess almost any programmer who uses .NET will now say this pattern is a piece of cake. That it is the best-known pattern used on the platform. However, even the simplest and well-known problem domain will have secret areas which you have never looked at. So, let’s describe the whole thing from the beginning for the first-timers and all the rest (so that each of you could remember the basics). Don’t skip these paragraphs — I am watching you!


If I ask what is IDisposable, you will surely say that it is


public interface IDisposable
{
    void Dispose();
}

What is the purpose of the interface? I mean, why do we need to clear up memory at all if we have a smart Garbage Collector that clears the memory instead of us, so we even don’t have to think about it. However, there are some small details.


This chapter was translated from Russian jointly by author and by professional translators. You can help us with translation from Russian or English into any other language, primarily into Chinese or German.

Also, if you want thank us, the best way you can do that is to give us a star on github or to fork repository github/sidristij/dotnetbook.
Read more →
Total votes 18: ↑17 and ↓1+16
Comments0

CLRium #5: Всё-всё-всё о GC и не только. Питер и Москва

Reading time2 min
Views4.1K


За окном бушует весна и гололед, а мы решили провести семинар CLRium #5, который на этот раз будет посвящен целиком и полностью самому низкому уровню: подсистемой управления памятью.


Я, Станислав Сидристый, автор книги .NET Platform Architecture, решился объединить разрозненную по всему интернету информацию и сделать большой семинар, который будет почти полностью посвящен теме управления памятью. Поверьте: можно смело назначать собеседования сразу после семинара. Вопросы, которые будут касаться управлением памятью вы ответите очень глубоко.


Шесть из десяти докладов раскроют тему управления памятью, алгоритмов и причин выбора алгоритмов работы GC так глубоко, как не сможет раскрыть ни одна конференция: ведь ни на одной конференции никто не даст выступить с докладом на 4,5 часа (6 докладов по 45 минут)


Ну и как заведено: все подробности под катом

Читать дальше →
Total votes 21: ↑21 and ↓0+21
Comments0

Memory and Span pt.1

Reading time7 min
Views3.5K

Starting from .NET Core 2.0 and .NET Framework 4.5 we can use new data types: Span and Memory. To use them, you just need to install the System.Memory nuget package:


PM> Install-Package System.Memory

These data types are notable because the CLR team has done a great job to implement their special support inside the code of .NET Core 2.1+ JIT compiler by embedding these data types right into the core. What kind of data types are these and why are they worth a whole chapter?


If we talk about problems that made these types appear, I should name three of them. The first one is unmanaged code.


Both the language and the platform have existed for many years along with means to work with unmanaged code. So, why release another API to work with unmanaged code if the former basically existed for many years? To answer this question, we should understand what we lacked before.


This chapter was translated from Russian jointly by author and by professional translators. You can help us with translation from Russian or English into any other language, primarily into Chinese or German.

Also, if you want thank us, the best way you can do that is to give us a star on github or to fork repository github/sidristij/dotnetbook.
Read more →
Total votes 22: ↑21 and ↓1+20
Comments2

.NET Reference Types vs Value Types. Part 2

Reading time10 min
Views3.1K


The Object base type and implementation of interfaces. Boxing


It seems we came through hell and high water and can nail any interview, even the one for .NET CLR team. However, let's not rush to microsoft.com and search for vacancies. Now, we need to understand how value types inherit an object if they contain neither a reference to SyncBlockIndex, not a pointer to a virtual methods table. This will completely explain our system of types and all pieces of a puzzle will find their places. However, we will need more than one sentence.


Now, let's remember again how value types are allocated in memory. They get the place in memory right where they are. Reference types get allocation on the heap of small and large objects. They always give a reference to the place on the heap where the object is. Each value type has such methods as ToString, Equals and GetHashCode. They are virtual and overridable, but don’t allow to inherit a value type by overriding methods. If value types used overridable methods, they would need a virtual methods table to route calls. This would lead to the problems of passing structures to unmanaged world: extra fields would go there. As a result, there are descriptions of value type methods somewhere, but you cannot access them directly via a virtual methods table.


This may bring the idea that the lack of inheritance is artificial


This chapter was translated from Russian jointly by author and by professional translators. You can help us with translation from Russian or English into any other language, primarily into Chinese or German.

Also, if you want thank us, the best way you can do that is to give us a star on github or to fork repository github/sidristij/dotnetbook.
Read more →
Total votes 34: ↑34 and ↓0+34
Comments0

.NET Reference Types vs Value Types. Part 1

Reading time16 min
Views7K

First, let’s talk about Reference Types and Value Types. I think people don’t really understand the differences and benefits of both. They usually say reference types store content on the heap and value types store content on the stack, which is wrong.


Let’s discuss the real differences:


  • A value type: its value is an entire structure. The value of a reference type is a reference to an object. – A structure in memory: value types contain only the data you indicated. Reference types also contain two system fields. The first one stores 'SyncBlockIndex', the second one stores the information about a type, including the information about a Virtual Methods Table (VMT).
  • Reference types can have methods that are overridden when inherited. Value types cannot be inherited.
  • You should allocate space on the heap for an instance of a reference type. A value type can be allocated on the stack, or it becomes the part of a reference type. This sufficiently increases the performance of some algorithms.

However, there are common features:


  • Both subclasses can inherit the object type and become its representatives.

Let’s look closer at each feature.


This chapter was translated from Russian jointly by author and by professional translators. You can help us with translation from Russian or English into any other language, primarily into Chinese or German.

Also, if you want thank us, the best way you can do that is to give us a star on github or to fork repository github/sidristij/dotnetbook.

Read more →
Total votes 33: ↑32 and ↓1+31
Comments1

Встреча .NET сообщества на CLRium #4 + онлайн

Reading time3 min
Views2.6K

Вы любите продуктовые доклады? Я — нет. А вы любите доклады, не относящиеся к теме конференции? Я — категорически нет. Складывается ощущение что я плачу за чужие амбиции и отсутствие контента. Потому мы делаем CLRium 4: где собираем все самое последнее, полезное… И самое главное — кишочки!


Теперь, помимо докладов будет жаркая дискуссия между спикерами по возможностям C# 8.0, которые полны неоднозначных моментов. И поверьте, будет жара: я многие моменты не приемлю, а вот второй спикер, Александр Кугушев уверяет что они так полезны, что хоть завтра — в прод. Наталия Цвилих придерживается смешанной точки зрения… Интереснейшая получится беседа, я вам обещаю.


Почитать и зарегистрироваться



cool Примеры статей и полный список тем выступлений — под катом
Читать дальше →
Total votes 11: ↑10 and ↓1+9
Comments10

Встреча .Net сообщества на CLRium #4 + онлайн. Куда движутся CoreCLR и C#. Приглашаются все

Reading time3 min
Views5.9K

Я не люблю заезженное слово «конференция». Это — встреча разработчиков с общими интересами, которые хотят послушать о будущем своей любимой платформы, а также о трюках, которые позволяют обходить правила, установленные в .NET Framework. Формат встречи — это десять слотов, которые заполнены только выжимкой самого современного, иногда даже еще не вышедшего функционала. Это как раз тот самый формат, когда нет необходимости забивать сетку докладами, которые не имеют никакого отношения к теме конференции. Наборот: идет плотная работа над отсевом не перспективных не относящихся к нашей платформе тем.


Я надеюсь, в вашей памяти теплятся еще прошлые версии CLRium. Я помню и время от времени поглядываю на ваши многочисленные отзывы, которые греют мое желание провести все еще раз. Причем на этот раз — с уклоном в будущее. А у меня по поводу будущего есть спойлер: .NET Framework будет закрыт в угоду Core CLR. Почему? Приходите и по цене одной заправки автомобиля вы все узнаете сами.


Почему я приглашаю всех? Темы встречи все как на подбор и позволяют окунуться в настоящее нашей opensource платформы. Вот честно, я бы сам сходил: разбираем эволюцию функционала CoreCLR: от 2.0 от 3.0, отладку при помощи самописного отладчика, богатейшие и очень спорные возможности C# 7.*, 8.0, Garbage Collector API, новые средства наделения свойствами управляемости неуправляемых ресурсов и многое другое.


Почитать и зарегистрироваться



cool Примеры статей и полный список тем выступлений — под катом
Читать дальше →
Total votes 28: ↑27 and ↓1+26
Comments8

CLRium #4: Встреча .NET сообщества

Reading time2 min
Views3K


GC API, C# 8.0, Global Tools, Span, Memory, System.IO.Pipeline, чего ждать в будущем

Рассуждая с коллегами о вопросах развития технологий, мы как-то пришли к выводу что в тот момент, когда выныриваешь из кода и прочих задач и бросаешь взгляд либо в сторону Хабра, либо в сторону бесконечных тематических лент Телеграма возникает странное чувство, что что-то пропустил. И чувство это знакомо каждому: профессия у нас такая, что не дает расслабиться. Причем даже если подписаться на каналы, RSS ленты и прочие источники, возникнет другая проблема: чувство усталости от потока информации (зачастую, мусорной). Как успеть за прогрессом, не теряя драгоценного времени?


Темой четвертой серии CLRium станут как обычно — самые последние последние наработки из мира .NET: мы в течении одного дня расскажем подробнее о том, что уже можно потрогать и бегло о том — что только планируется. Посещение данного мероприятия — прекрасный способ освежить понимание вектора развития нашей прекрасной платформы и узнать то, на что обычно не хватает времени и решить для себя что-нибудь попробовать в ближайшем будущем.


  • 19 октября в Санкт-Петербурге + online, в офисе компании Epam Systems
  • 26 октября в Москве
Читать дальше →
Total votes 21: ↑19 and ↓2+17
Comments2

Information

Rating
Does not participate
Location
Санкт-Петербург, Санкт-Петербург и область, Россия
Date of birth
Registered
Activity