首页 > 编程语言 > 详细

Thread 类创建线程

时间:2021-01-08 22:38:46      阅读:20      评论:0      收藏:0      [点我收藏+]

创建一个线程,使用Thread类创建线程时,只需提供线程入口即可。(线程入口使程序知道该让这个线程干什么事)

在C#中,线程入口是通过ThreadStart代理(delegate)来提供的,你可以把ThreadStart理解为一个函数指针,指向线程要执行的函数,当调用Thread.Start()方法后,线程就开始执行ThreadStart所代表或者说指向的函数。

新建一个控制台应用程序(Console Application),编写完全控制一个线程的代码示例:

 

using System;
using System.Threading; 

namespace ThreadTest
{
  public class Alpha
  {
      public void Beta()
      {
        while (true)
        {
          Console.WriteLine("Alpha.Beta is running in its own thread.");
        }
      }
  }; 

  public class Simple
  {
      public static int Main()
      {
        Console.WriteLine("Thread Start/Stop/Join Sample");

                Alpha oAlpha = new Alpha();
        file://这里创建一个线程,使之执行Alpha类的Beta()方法
        Thread oThread = new Thread(new ThreadStart(oAlpha.Beta));
        oThread.Start();
        while (!oThread.IsAlive)
               Thread.Sleep(1);
        oThread.Abort();
        oThread.Join();
        Console.WriteLine();
        Console.WriteLine("Alpha.Beta has finished"); 
        try 
        {
          Console.WriteLine("Try to restart the Alpha.Beta thread");
          oThread.Start();
        }
        catch (ThreadStateException) 
        {
          Console.Write("ThreadStateException trying to restart Alpha.Beta. ");
          Console.WriteLine("Expected since aborted threads cannot be restarted.");
          Console.ReadLine();
        }
        return 0;
      }
  }
}

Thread 类创建线程

原文:https://www.cnblogs.com/qqhewei/p/14253169.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!