Skip to content

Instantly share code, notes, and snippets.

[MethodImpl(MethodImplOptions.AggressiveOptimization)]
static void Test()
{
var obj = new object();
// Run a garbage collection in 1 second
Task.Delay(1000).ContinueWith(_ => { GC.Collect(); });
// As soon as MyNativeMethod is called, there are no more references to obj
MyNativeMethod(new WeakReference(obj));
void Test()
{
var obj = new Object();
DoStuffWithObj(obj);
// At this point, the GC knows the object isn't used anymore and may collect obj
DoStuff();
}
var taskCompletionSource = new TaskCompletionSource();
MyDelegateType myDelegate = () => taskCompletionSource.SetResult();
NativeMethods.MyNativeMethod(myDelegate);
await taskCompletionSource.Task;
GC.KeepAlive(myDelegate);
public unsafe class Getter
{
private delegate*<Obj, SomeStruct*, SomeStruct*> _functionPointer;
public Getter(string propName)
{
var methodInfo = typeof(Obj).GetProperty(propName).GetGetMethod();
_functionPointer = (delegate*<Obj, SomeStruct*, SomeStruct*>)methodInfo.MethodHandle.GetFunctionPointer();
}
public class MyClass
{
public static LargeStruct StaticMethod(MyClass obj)
{
// ...
}
public LargeStruct InstanceMethod()
{
// ...
public struct SomeStruct
{
public int Value1;
}
public unsafe class Getter
{
private delegate*<Obj, SomeStruct> _functionPointer;
public Getter(string propName)
{
var methodInfo = typeof(Obj).GetProperty(propName).GetGetMethod();
_functionPointer = (delegate*<Obj, SomeStruct>)methodInfo.MethodHandle.GetFunctionPointer();
}
using System;
using System.Runtime.InteropServices;
namespace ManagedDotnetProfiler;
public class DllMain
{
[UnmanagedCallersOnly(EntryPoint = "DllGetClassObject")]
public static unsafe int DllGetClassObject(Guid* rclsid, Guid* riid, IntPtr* ppv)
{
@kevingosse
kevingosse / Program.cs
Created March 26, 2022 15:18
Extract native code from dynamic method
using Microsoft.Diagnostics.Runtime;
using System;
using System.Linq;
namespace ExtractDynamicMethod
{
internal class Program
{
static void Main(string[] args)
{
[MemoryDiagnoser]
public class EmptyEnumerator
{
[Benchmark(Baseline = true)] public bool ArrayEmpty() => Array.Empty<string>().GetEnumerator().MoveNext();
[Benchmark] public bool ArrayEmptyAsEnumerable() => ((IEnumerable<string>)Array.Empty<string>()).GetEnumerator().MoveNext();
[Benchmark] public bool ArrayEmptyForEach()
{
foreach (var _ in Array.Empty<string>())