Что такое reference assemblies
Перейти к содержимому

Что такое reference assemblies

  • автор:

When to create and distribute «reference assemblies»?

C# 7.1 introduced a few new command line parameters to help create «reference assemblies». By documentation it outputs an assembly which:

have their method bodies replaced with a single throw null body, but include all members except anonymous types.

That means it changes less often than the full assembly—many common development activities don’t change the interface, only the implementation. That means that incremental builds can be much faster- .

We will be introducing a second concept, which is «reference assemblies» (also called skeleton assemblies). [—] They will be used for build scenarios.

  • usually you also care about execution and the implementation assembly already contains all the data from reference assembly,
  • quite often you don’t care about that minor performance difference on loading,
  • and most importantly — usually you don’t have that stripped-down reference assembly available (distributed) at all.

It’s usefulness seems rather niche.

So, I wonder about the general assembly producer side of things — when should one consider explicitly using those new compiler flags to create a reference assembly? Does it have a any practical use outside Roslyn itself at all?

asked Apr 11, 2018 at 14:20
Imre Pühvel Imre Pühvel
4,508 1 1 gold badge 36 36 silver badges 49 49 bronze badges

You have been using such assemblies for the past 8 years. That is how the .NET 4.x framework reference assemblies are implemented. Stored in the c:\program files (x86)\reference assemblies directory. They provide a basic guarantee that the (many) changes that Microsoft has made to the framework code does not break any existing program. Such breakage can be excessively painful. And happened in the past, the WaitHandle.WaitOne(int) overload got added in a .NET 2.0 service pack. Kaboom on a machine that wasn’t updated.

Apr 11, 2018 at 14:29

This matters a lot more to Microsoft than it does to us. We can simply increment the [AssemblyVersion], forcing our clients to rebuild their program.

Apr 11, 2018 at 14:33

In old PCL days, some NuGet packages use their own tricks to generate assemblies for reference purposes only, for PCL projects to consume, and other real assemblies for each target platforms. They might benefit from the Roslyn feature, but with the death of PCL, .NET Standard is far better an alternative.

Apr 12, 2018 at 0:12

1 Answer 1

The motivation for this feature is indeed build scenarios, but they’re not specific to Roslyn; they’re your build scenarios, too.

When you build your project, the build engine (MSBuild) needs to decide whether each output of the build is up to date with respect to its inputs. For example, if you don’t change anything and just run build twice in a row, the second time doesn’t need to invoke the C# compiler: the assembly was already correct.

Reference assemblies allow skipping the compile step for assemblies in more scenarios, so your builds can be faster. I think an example would help illustrate.

Suppose you have a solution containing B.exe that depends on A.dll .

The compiler command line for B would look something like

csc.exe /out:B.exe /r. \A\bin\A.dll Program.cs 

And its inputs would be

  • The source for B ( Program.cs )
  • The assembly for A.

If you change the source of A and build your solution, the compiler must run for A, producing a new A.dll . Then, since A.dll is an input to the compilation of B, B has to be recompiled, too.

Using a reference assembly for A changes this slightly

csc.exe /out:B.exe /r. \A\bin\ref\A.dll Program.cs 

The input for A is now its reference assembly, rather than its implementation/normal assembly.

Since the reference assembly is smaller than the full assembly, that has a minor effect on build time all by itself. But that’s not enough to justify this feature. What’s important is that the compiler only cares about the public API surface of the passed-in references. If an internal implementation detail of the assembly has changed, assemblies that reference it do not need to be recompiled to pick up the new behavior. As @Hans Passant mentions in comments, this is how the .NET Framework itself can deliver compatible performance improvements and bug fixes on unchanged user code.

The benefit of the reference assemblies feature comes from the MSBuild work done to use them. Suppose you change an internal implementation detail in A but don’t change its public interface. On the next build,

  • The compiler must run for A, because source files for A changed.
  • The compiler emits both A.dll (with the changed implementation) and ref\A.dll , which is identical to the previous reference assembly.
  • Since ref\A.dll is identical to the previous output, it does not get copied to A’s output folder.
  • When it is time for B’s compiler to run, it sees that none of its inputs have changed—neither B’s own code, nor A’s reference assembly, so the compiler doesn’t have to run.
  • B then copies the updated A.dll to its output and is ready to run with the new behavior.

The effect of skipping downstream compilation can compound as you go along in a large solution—changing a comment in .Utilities.dll no longer requires building everything!

Many changes involve changing both the public API surface and the internal implementation, so this change doesn’t speed up all builds, but it does speed up many builds.

.NET — What are Reference Assemblies?

What is the purpose of the Reference Assemblies directory under Program Files?

Reference Assemblies constitutes the published API for a specific version of the framework.

When you target a specific version of the framework in Visual Studio, the compiler uses type information from Reference Assemblies, and not from assemblies in the GAC. Not yet. Not until runtime.

Reference Assemblies contain no implementation, only metadata.

C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v3.5 C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0 C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5 C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5.1 C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5.2 C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6 C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.1 C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.2 C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.7 C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.X

How do these assemblies compare to those in C:\Windows\Microsoft.NET\Framework\v4.0.30319 ?
How are they used?

Let’s look at mscorlib.dll .

The Reference Assembly is smaller. It contains no implemetation, only metadata.

The Reference Assembly is older. It represents the assembly as it appeared when it was originally released, without any patches.

Since the Reference Assembly contains only metadata, the only patches that we are interested in, are changes to the API. Methods that were added. Interfaces that were changed.
When you build against a Reference Assembly you are targeting a version of the framework as it appeared, when it was publicly released, as opposed to the framework in your machine’s GAC.

The concept is similar to C++ Include Files.

When you #include , the compiler permits you to call only those methods that are present in that version of Windows. If you are compiling for Windows 8, you don’t want to use an API that was added for Windows 10.

Reference Assemblies что это за программа и нужна ли она?

Добрый день ребята Будем сегодня знакомиться с такой прогой как Reference Assemblies — я расскажу что это такое и вы сможете понять нужна вам эта программа или нет. Reference Assemblies относится не к простым программам, а к тем, о которых мало кто что знает, а все потому что это больше вспомогательный компонент, чем отдельное приложение. Данный компонент нужен для правильной работы других программ.

Ситуация необычная — небольшая популярность Reference Assemblies может стать поводом появления вирусов, которые будут косить под эту прогу. Я проанализировал интернет и пришел к выводу, что Reference Assemblies относится к среде разработки Visual Studio, в этой среде (или редакторе) программеры создают приложения, функции, библиотеки. И как я понимаю, Reference Assemblies это дополнение, содержащее уже готовый набор каких-то функций.

Часто программа Reference Assemblies имеет свою папку в директории C:\Program Files, при этом стоит отметить что студия Visual Studio находится в отдельной папке и не пересекается с папкой Reference Assemblies, вот так вот немного закручено…

Нашел в сети такую картинку:

Ну тут видно что само окно это от студии Visual Studio и тут предлагается что-то выбрать.. Но что именно — неизвестно..

Reference Assemblies у вас может быть на компьютере не только тогда, когда стоит студия Visual Studio, но и тогда когда у вас например есть пакеты Фреймворка. Удалять Reference Assemblies ну никак не стоит, это может спровоцировать глюки и лаги в компе — оно вам нужно?

Я посмотрел у себя на компе — папка Reference Assemblies есть, вот она:

Именно эта папка находится в C:\Program Files, я потом пошел в C:\Program Files (x86) и там тоже была эта папка:

Я посмотрел что внутри папок — ничего особенного, только непонятные папки там и библиотеки. Если зайти в папку, то там идет сначала папка Microsoft, потом идет папка Framework, потом идут две папки v3.0 и v3.5, и внутри этих папок примерно одно и тоже. Ну вот например что в папке v3.5:

ОЧЕНЬ ВАЖНЫЙ МОМЕНТ. Я обратил внимание на то, что сама папка Reference Assemblies изменена была аж в 2009-том году — то есть в принципе тогда когда и делали винду и все такое. Вот доказательства, смотрите:

Это только лишний раз показывает что папка Reference Assemblies относится к системе и удалять ее не нужно просто так

Надумал я кое что проверить — зажал кнопульки Win + E, открылось окно где у меня диски все, там я зашел на системный диск, и в окне в правом верхнем углу было поле, туда написал я слово Reference:

Дальше я ждал, ждал.. и вот что нашлось:

И это еще не все. Видите? Эта штука Reference Assemblies — не серая мышка какая-то, а видимо весомый компонент винды все таки..

Но как я уже писал, под данную программу может маскироваться вирус — ибо о проге инфы мало, а та инфа что есть, то она указывает на то что это системная штука. Вот вирусописатели этим могут воспользоваться — подстроят все так чтобы вы думали что это не вирус. Что нужно сделать чтобы исключить заражение вирусом? Первое — это просканировать машину утилитой AdwCleaner:

Вы не смотрите на немецкий язык, это я картинку для примера нашел, AdwCleaner идет на русском и бесплатная эта утилита, скачать в интернете легко, ибо есть она на каждом углу. Данная утилита очистит комп от всего левого и вредного — это псевдовирусы, они не оч опасны, но очень много делают пакостей. Так вот, второе что вам нужно сделать, это проверить комп утилитой Доктор Веб КуреИТ — это уже мощнейшая утилита которая находит опасные и оч опасные вирусы, трояны, черви. Проверить обязательно нужно! Оцените как она выглядит:

Как бы я мог оценить работу Доктора Веба КуреИТ? Работает утилита хорошо, также бесплатная, скачать не проблем. Один косяк в утилите есть — она просит согласится с тем что будет отправляться анонимная инфа о проверке. Это абсолютно безопасно и данный шаг сделан для улучшения работы самой утилиты

Вот и все ребята — я искренно буду надеяться что я смог вам помочь данной статье. Пока..

можно ли удалить папку Reference Assemblies из Program Files? Я пытаюсь увеличить свободное место на диске.

Можно удалить конечно, но после этого у Вас ни одна програма\игра требующая Microsoft .NET Framework не запустится!
Лучше поступить так!
1 Удалить\перенести с C: все программы и игры на другой раздел
2 Удалить\перенести с C: все картинки видео и музыку на другой раздел
3 Почистить папку загрузки
4 Почистить папки загрузки различных программ загрузчиков (битторрент, шареман, zona и прочие)
5 Почистить папку Temp
6 Всё что находится на рабочем столе — находится на диске C: — таким образом удаляем\переносим всё с рабочего стола (кроме ярлыков)
7 Запускаем стандартную очистку диска
Ну вот после этого у вас должно появиться свободное место! )))

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *