C# Thread 线程的停止和恢复



/*
因为公用语言运行时管理了所有的托管的线程,同样它能在每个线程内抛出异常。Abort方法能在目标线程中抛出一个ThreadAbortException异常从而导致目标线程的终止。不过Abort方法被调用后,目标线程可能并不是马上就终止了。因为只要目标线程正在调用非托管的代码而且还没有返回的话,该线程就不会立即终止。而如果目标线程在调用非托管的代码而且陷入了一个死循环的话,该目标线程就根本不会终止。不过这种情况只是一些特例,更多的情况是目标线程在调用托管的代码,一旦Abort被调用那么该线程就立即终止了。
*/
using System;
 
using System.Windows;
 
using System.Threading;

namespace WpfApp5
{
     
    /// 
    /// MainWindow.xaml 的交互逻辑
    /// 
    public partial class MainWindow : Window
    {
     
        public MainWindow()
        {
     
            InitializeComponent();

            thread = new Thread(ooooMethod);
            thread.IsBackground = true;
        }

        private void ooooMethod(Object ooo)
        {
     
            while (true)
            {
     
                Dispatcher.Invoke(() => xLabel.Content = g_i++.ToString());
                System.Threading.Thread.Sleep((int) ooo);
            }
        }

        int g_i =0 ;

        Thread thread;

        void start()
        {
     
            thread.Start(100);
            xLabel.Content = "Thread Started";
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
     

            if ((thread.ThreadState ==ThreadState.Aborted))
            {
     
                thread = new Thread(ooooMethod);
                thread.IsBackground = true;
            }
            if (thread.ThreadState == (ThreadState.Unstarted|ThreadState.Background))
            {
     
                start();
            }
   
        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
     
            thread.Abort();
        }
    }
}

你可能感兴趣的:(C#知识点)