Csharp/C Sharp/Thread/Thread Interupt Destroy — различия между версиями

Материал из .Net Framework эксперт
Перейти к: навигация, поиск
м (1 версия)
 
(нет различий)

Версия 15:31, 26 мая 2010

Catch ThreadAbortException

 
using System;
using System.Threading;
class MainClass
{
    private static void DisplayMessage()
    {
        try
        {
            while (true)
            {
                Console.WriteLine("{0} : DisplayMessage thread active", DateTime.Now.ToString("HH:mm:ss.ffff"));
                Thread.Sleep(1000);
            }
        }
        catch (ThreadAbortException ex)
        {
            Console.WriteLine("{0} : DisplayMessage thread terminating - {1}",
               DateTime.Now.ToString("HH:mm:ss.ffff"),
              (string)ex.ExceptionState);
        }
        Console.WriteLine("{0} : nothing is called after the catch block",
            DateTime.Now.ToString("HH:mm:ss.ffff"));
    }
    public static void Main()
    {
        Thread thread = new Thread(DisplayMessage);
        Console.WriteLine("{0} : Starting DisplayMessage thread" +
            " - press Enter to terminate.",
            DateTime.Now.ToString("HH:mm:ss.ffff"));
        thread.Start();
        System.Console.ReadLine();
        thread.Abort("User pressed Enter");
        thread.Join();
    }
}


Destroying Threads

/*
 * C# Programmers Pocket Consultant
 * Author: Gregory S. MacBeth
 * Email: gmacbeth@comporium.net
 * Create Date: June 27, 2003
 * Last Modified Date:
 * Version: 1
 */
using System;
using System.Threading;
namespace Client.Chapter_15___Threading
{
  public class DestroyingThreads
  {
    static int MyCount = 0;
    static void Main(string[] args)
    {
      MyClassThread me = new MyClassThread();
      Thread MyNewThread = new Thread(new ThreadStart(me.MyThread));
      MyNewThread.Start();
      if (MyCount == 0)
        MyNewThread.Abort();
    }
  }
  class MyClassThread
  {
    public void MyThread()
    {
    }
  }
}