Let's go

线程处理

案例一、

        public static void Main()
        {
            // Create the token source.
            CancellationTokenSource cts = new CancellationTokenSource();

            // Pass the token to the cancelable operation.
            ThreadPool.QueueUserWorkItem(new WaitCallback(DoSomeWork), cts.Token);
            Thread.Sleep(1000);

            // Request cancellation.
            cts.Cancel();
            Console.WriteLine("Cancellation set in token source...");
            Thread.Sleep(2500);
            // Cancellation should have happened, so call Dispose.
            cts.Dispose();
            Console.ReadLine();
        }

        // Thread 2: The listener
        static void DoSomeWork(object obj)
        {
            CancellationToken token = (CancellationToken)obj;

            for (int i = 0; i < 100000; i++)
            {
                if (token.IsCancellationRequested)
                {
                    Console.WriteLine("In iteration {0}, cancellation has been requested...",
                                      i + 1);
                    // Perform cleanup if necessary.
                    //...
                    // Terminate the operation.
                    break;
                }
                // Simulate some work.
                //Thread.SpinWait(500000);
                Console.WriteLine("{0}...", i + 1);
            }
        }

 2、等待线程结束

while (ls_jy_Thread.ThreadState != ThreadState.Aborted)
{
  Dll_Class.ls_start = true;
  //当调用Abort方法后,如果thread线程的状态不为Aborted,主线程就一直在这里做循环,直到thread线程的状态变为Aborted为止
  Thread.Sleep(100);
}

 

。。。

posted @ 2021-07-14 13:39  chenze  阅读(53)  评论(0编辑  收藏  举报
有事您Q我