Thread类负责在多线程编程中创建和管理线程。它提供了一个称为CurrentThread的属性来检查当前正在运行的线程。换句话说,此属性的值指示当前正在运行的线程。
用法:public static Thread CurrentThread { get; }
返回值:该属性返回代表当前运行线程的线程。
以下示例程序旨在说明CurrentThread属性的用法:
。
范例1:
// C# program to illustrate the
// use of CurrentThread property
using System;
using System.Threading;
class GFG {
// Main Method
static public void Main()
{
Thread thr;
// Get the reference of main Thread
// Using CurrentThread property
thr = Thread.CurrentThread;
thr.Name = "Main thread";
Console.WriteLine("Name of current running "+
"thread:{0}", thr.Name);
}
}
输出:
Name of current running thread:Main thread
范例2:
// C# program to illustrate the
// use of CurrentThread property
using System;
using System.Threading;
class GFG {
// Display the id of each thread
// Using CurrentThread and
// ManagedThreadId properties
public static void Myjob()
{
Console.WriteLine("Thread Id:{0}",
Thread.CurrentThread.ManagedThreadId);
}
// Main method
static public void Main()
{
// Creating multiple threads
ThreadStart value = new ThreadStart(Myjob);
for (int q = 1; q <= 7; ++q)
{
Thread mythread = new Thread(value);
mythread.Start();
}
}
}
输出:
Thread Id:3 Thread Id:8 Thread Id:9 Thread Id:6 Thread Id:5 Thread Id:7 Thread Id:4
参考:
相关用法
- C# Dictionary.Values用法及代码示例
- C# Dictionary.Item[]用法及代码示例
- C# SortedDictionary.Values用法及代码示例
- C# SortedDictionary.Keys用法及代码示例
- C# SortedDictionary.Count用法及代码示例
- C# SortedDictionary.Item[]用法及代码示例
- C# Dictionary.Keys用法及代码示例
- C# Dictionary.Count用法及代码示例
- C# Queue.Count用法及代码示例
- C# Queue.IsSynchronized用法及代码示例
- C# Stack.Count用法及代码示例
- C# Stack.IsSynchronized用法及代码示例
注:本文由纯净天空筛选整理自ankita_saini大神的英文原创作品 Thread.CurrentThread Property in C#。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。