Skip to content

Instantly share code, notes, and snippets.

View Criteo-dotnet-blog's full-sized avatar

Criteo-dotnet-blog

View GitHub Profile
StringBuilder stringBuilder2 = new StringBuilder(1024);
if (Microsoft.Win32.NativeMethods.GetModuleFileNameEx(
  safeProcessHandle, 
  new HandleRef(null, handle), 
  stringBuilder2, 
  stringBuilder2.Capacity * 2
 ) == 0)
[DllImport("psapi.dll", BestFitMapping = false, CharSet = CharSet.Auto, SetLastError = true)]
private static extern int GetModuleFileNameEx(SafeProcessHandle processHandle, IntPtr moduleHandle, StringBuilder baseName, int size);
private static Func<Process, string> GetProcessNameAccessor()
{
var param = Expression.Parameter(typeof(Process), "arg");
var processInfoMember = Expression.Field(param, "processInfo");
var processNameMember = Expression.Field(processInfoMember, "processName");
var lambda = Expression.Lambda(typeof(Func<Process, string>), processNameMember, param);
return (Func<Process, string>)lambda.Compile();
}
private static Type _processInfoType = null;
private static FieldInfo _processNameField = null;
public static string GetProcessNameByReflection(Process p)
{
var processInfoField = typeof(System.Diagnostics.Process)
.GetField("processInfo", BindingFlags.Instance | BindingFlags.NonPublic);
var processInfo = processInfoField.GetValue(p);
if (_processInfoType == null)
{
private readonly StringBuilder _baseNameBuilder = new StringBuilder(1024);
public static string GetProcessNameNative(Process p)
{
_baseNameBuilder.Clear();
if (GetModuleFileNameEx(p.SafeHandle, IntPtr.Zero, _baseNameBuilder, _baseNameBuilder.Capacity) == 0)
{
_baseNameBuilder.Append("???");
}
return _baseNameBuilder.ToString();
public static bool IsProcessRunning(int processId)
{
return IsProcessRunning(processId, GetProcessIds());
}
public static SafeProcessHandle OpenProcess(int processId, int access, bool throwIfExited)
{
SafeProcessHandle safeProcessHandle = NativeMethods.OpenProcess(access, false, processId);
int lastWin32Error = Marshal.GetLastWin32Error();
if (!safeProcessHandle.IsInvalid)
return safeProcessHandle;
// error handling
if (processId == 0)
throw new Win32Exception(5);
_workers = new Task[workerCount];
for (int i = 0; i < workerCount; i++)
{
_workers[i] = Task.Run(async () =>
{
while (true)
{
lock (_lock)
{
Thread.Sleep(5);
private void OnContentionStop(ContentionTraceData data)
{
ContentionInfo info = _contentionStore.GetContentionInfo(data.ProcessID, data.ThreadID);
if (info == null)
return;
// unlucky case when we start to listen just after the ContentionStart event
if (info.ContentionStartRelativeMSec == 0)
return;
private void OnContentionStart(ContentionTraceData data)
{
ContentionInfo info = _contentionStore.GetContentionInfo(data.ProcessID, data.ThreadID);
if (info == null)
return;
info.TimeStamp = data.TimeStamp;
info.ContentionStartRelativeMSec = data.TimeStampRelativeMSec;
}