C#中的多线程

*********************************************************************************************************
//创建线程
using System;
using System.Threading;
class Class1
{
   public void Method1()
   {
      Console.WriteLine("Method1 is the starting point of execution of the thread");
   }
   public static void Main()
   {
      Class1 newClass = new Class1();
      Thread Thread1 = new Thread(new ThreadStart(newClass.Method1));
   }
}

//启动线程
Thread1.Start();

//用相关名称为线程命名
Thread.Name = "Update Records Thread";

//用特性了解正在执行的线程的状态
IsAlive
ThreadState

//终止线程-合并线程
Thread1.Abort();
Thread1.Join();
**通常调用Abort()后线程不会立即终止,需要Join()配合


//挂起线程-从挂起点重新开始执行线程
Thread1.Suspend();
Thread1.Resume();
**如果线程挂起了本身,需要另一个线程调用Resume()来重新开始这个线程

//线程休眠
Thread.Sleep(2000);

//example
using System;
using System.Threading;
class Class1
{
   public void Method1()
   {
      Console.WriteLine("Method1 is the starting point of execution of the thread");
   }
   public static void Main()
   {
      Class1 newClass = new Class1();
      Thread Thread1 = new Thread(new ThreadStart(newClass.Method1));
      Thread1.Name = "Sample Thread";
      Thread1.Start();
      Console.WriteLine("The execution of Sample Thread has started.");
      Thread1.Abort();
   }
}

//线程状态
Thread.Start()  -  Running
Thread.Sleep()  -  WaitSleepJoin
Thread.Suspend() -  从另一个线程中调用-SuspendRequested;执行Thread.Suspned()-Suspended
Thread.Resume()  -  Running
Thread.Abort()  -  从另一个线程中调用-AbortRequested;  执行Thread.Abort()-Aborted

//线程优先级
Highest
AboveNormal
Normal
BelowNormal / Lowest

Thread Thread1 = new Thread(new ThreadStart(newClass.Method1));
Thread1.Priority = ThreadPriority.Highest;
**Highest优先级会停止执行系统上正在运行的所有线程

//同步
同步确保在任何时刻仅仅一个线程可以访问某个变量
lock(variablel)
{
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值