Not that I’m proud of that, but to circumvent the limitations of CLR and C# I sometimes had to use reflection, code generation, changing behavior depending on who’s calling etc.
However I think this code beats all that.
public static class HandleProvider
{
private static int _currentToken = typeof(object).GetConstructors()[0].MetadataToken;
private static ModuleHandle _moduleHandle = typeof(object).Module.ModuleHandle;
/// <summary>
/// This is an ugly hack to circumvent lack of useful public constructor on RuntimeMethodHandle struct
/// </summary>
/// <returns>Method handle of some method from mscorlib</returns>
[MethodImpl(MethodImplOptions.Synchronized)]
public static RuntimeMethodHandle GetNextHandle()
{
/* Since we need RuntimeMethodHandles and the struct does not have a constructor we can use, we need some other way of obtaining these.
* We're stealing them from mscorlib. We can (hopefully) do this, because it's only for AsyncType's Begin/End methods.
* Their handles are used (not that this is just internal implementation detail which can change and thus breaking my code) only
* as keys in the dicionary so we only need to have different ones, and we should be fine.
*/
return _moduleHandle.GetRuntimeMethodHandleFromMetadataToken(_currentToken++);
}
}
It’s a part of my effort to enable asyncronous calls on WCF proxies created via ChannelFactory. You can see the whole code here.