c# instantly kill thread with TerminateThread (danger)

Danger: dead lock or mem leak 
use only as Process.Kill() to exit app with defined exit code

 

        [DllImport("kernel32.dll")]
        static extern bool TerminateThread(int hThread, uint dwExitCode);

        //[STAThread]
        static void Main(string[] args)
        {     

            try
            {
                Thread t = new Thread(() =>
                    {
                       //code even interop
                    });
                t.IsBackground = true//check out this line
                t.Start();
                Console.Title = ("Hit Enter to stop");
                Console.ReadLine();
                uint dwExitCode = 0;
                TerminateThread(t.ManagedThreadId, dwExitCode); //and this line
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Console.ReadKey();
            }

        }

posted on 2012-03-14 11:55  无法显示此网页  阅读(748)  评论(0编辑  收藏  举报

导航