Skip to content

Instantly share code, notes, and snippets.

@jkotas
Created July 15, 2025 10:38
Show Gist options
  • Save jkotas/2d4f15056768c1b221a78684b4245fec to your computer and use it in GitHub Desktop.
Save jkotas/2d4f15056768c1b221a78684b4245fec to your computer and use it in GitHub Desktop.
Unhandled exception
using System;
using System.Runtime.InteropServices;
class Program
{
// Define a delegate that matches the LPTHREAD_START_ROUTINE signature:
// DWORD WINAPI ThreadProc(LPVOID lpParameter);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate uint ThreadProc(IntPtr lpParameter);
// Import CreateThread from kernel32.dll
[DllImport("kernel32.dll", SetLastError = true)]
private static extern IntPtr CreateThread(
IntPtr lpThreadAttributes,
UIntPtr dwStackSize,
ThreadProc lpStartAddress,
IntPtr lpParameter,
uint dwCreationFlags,
out uint lpThreadId);
// Import WaitForSingleObject and CloseHandle to synchronize and clean up
[DllImport("kernel32.dll", SetLastError = true)]
private static extern uint WaitForSingleObject(
IntPtr hHandle,
uint dwMilliseconds);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool CloseHandle(IntPtr hObject);
// Constants
private const uint INFINITE = 0xFFFFFFFF;
private const uint WAIT_OBJECT_0 = 0x00000000;
static void Main()
{
// Create the thread, pointing to our managed ThreadFunction
uint threadId;
IntPtr threadHandle = CreateThread(
IntPtr.Zero, // lpThreadAttributes
UIntPtr.Zero, // dwStackSize (0 = default)
ThreadFunction, // lpStartAddress
IntPtr.Zero, // lpParameter
0, // dwCreationFlags (0 = run immediately)
out threadId // receives the thread ID
);
if (threadHandle == IntPtr.Zero)
{
int err = Marshal.GetLastWin32Error();
Console.WriteLine($"CreateThread failed with error {err}");
return;
}
Console.WriteLine($"Thread {threadId} started.");
// Wait for the thread to finish
uint waitResult = WaitForSingleObject(threadHandle, INFINITE);
if (waitResult != WAIT_OBJECT_0)
{
Console.WriteLine("WaitForSingleObject failed or timed out.");
}
else
{
Console.WriteLine("Thread has exited.");
}
Thread.Sleep(-1);
}
// This is the method our thread will execute
private static uint ThreadFunction(IntPtr lpParameter)
{
throw new Exception("My exception");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment