Skip to content

Instantly share code, notes, and snippets.

@filipnavara
Last active March 10, 2019 16:05
Show Gist options
  • Save filipnavara/fe7a0fcdfdb76d8efd148d9476d4cd8c to your computer and use it in GitHub Desktop.
Save filipnavara/fe7a0fcdfdb76d8efd148d9476d4cd8c to your computer and use it in GitHub Desktop.
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;
using System.Threading;
namespace OverlappedBench
{
[InProcess]
public class Program
{
[Benchmark]
public unsafe void AllocOverlappedNull()
{
AllocOverlapped(null);
}
[Benchmark]
public unsafe void AllocOverlappedObject()
{
AllocOverlapped(IntPtr.Zero);
}
[Benchmark]
public unsafe void AllocOverlappedArray()
{
AllocOverlapped(new[] { IntPtr.Zero, IntPtr.Zero, IntPtr.Zero });
}
private unsafe void AllocOverlapped(object userObject)
{
Overlapped ov = new Overlapped();
var helper = new AsyncHelper();
IOCompletionCallback callback = helper.Callback;
NativeOverlapped* nativeOverlapped = ov.Pack(callback, userObject);
ThreadPool.UnsafeQueueNativeOverlapped(nativeOverlapped);
helper.Wait();
}
internal class AsyncHelper
{
ManualResetEvent _event;
internal AsyncHelper()
{
this._event = new ManualResetEvent(false);
}
internal bool Wait()
{
return this._event.WaitOne();
}
internal unsafe void Callback(uint errorCode, uint numBytes, NativeOverlapped* _overlapped)
{
try
{
this._event.Set();
}
finally
{
Overlapped.Free(_overlapped);
}
}
}
static void Main(string[] args)
{
BenchmarkRunner.Run<Program>();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment