Using kernel32 CreateThread/TerminateThread inside

2019-07-29 22:40发布

问题:

I have this code that I need to use, but what holds me back is that here it says that TerminateThread Applies to: desktop apps only. I wonder if I can use this code inside azure Worker role, specifically inside waiishost.exe process that I use to run the Worker thread in?

[DllImport("Library.dll")]
public static extern void InfiniteLoop();

[DllImport("kernel32")]
private static extern int CreateThread(
   IntPtr lpThreadAttributes,
   UInt32 dwStackSize,
   IntPtr lpStartAddress,
   IntPtr param,
   UInt32 dwCreationFlags,
   UInt32 lpThreadId
 );

[DllImport("Kernel32.dll", CharSet = CharSet.Auto)]
public static extern int TerminateThread(int hThread);

[DllImport("Kernel32.dll", CharSet = CharSet.Auto)]
public static extern int GetLastError();

private delegate int InvokeInfiniteLoop(IntPtr args);

static void Main(string[] args)
{
      InvokeInfiniteLoop invokeInfiniteLoop = (args1) =>
                                                    {
                                                        InfiniteLoop();
                                                        return 0;
                                                    };
     IntPtr infiniteLoopPtr = Marshal.GetFunctionPointerForDelegate(invokeInfiniteLoop);
     int handle = CreateThread(IntPtr.Zero, 0, infiniteLoopPtr, IntPtr.Zero, 0, 0);
     Thread.Sleep(TimeSpan.FromSeconds(5));
     int terminated = TerminateThread(handle);
     Console.WriteLine(terminated);
}

EDIT:

After further research looks like(as I suspected from the beginning) that this workaround is completely wrong. Creating and Terminating the unmanaged code will leak the stack. I will have to create a separate executable that will be terminated by Process.Kill();

回答1:

The "Applies to: desktop apps only" refers to the difference between Windows 8 Desktop application and Windows 8 Metro applications.