差异b / w Thread和ThreadStart [英] Difference b/w Thread and ThreadStart
问题描述
我正在学习线程概念,但我无法区分线程和ThreadStart。以下是我的代码....
Hi,I am learning threading concepts and I could not make out the difference b/w Thread and ThreadStart. Below is my code....
class Alpha
{
public void Beta()
{
for (int i = 0; i < 5;i++ )
{
Console.WriteLine("Alpha.Beta is running its own thread.......");
}
}
}
public class Simple
{
public static int Main()
{
Console.WriteLine("Thread Start/Stop/Join Sample");
Alpha oAlpha = new Alpha();
// Thread oThread = new Thread(new ThreadStart(oAlpha.Beta));
Thread oThread = new Thread(oAlpha.Beta);
oThread.Start();
while(!oThread.IsAlive);
Thread.Sleep(1);
// Thread oThread = new Thread(new ThreadStart(oAlpha.Beta));
Thread oThread = new Thread(oAlpha.Beta);
oThread.Start();
while (!oThread.IsAlive);
Thread.Sleep(1);
oThread.Join();
Console.WriteLine();
Console.WriteLine("Alpha.Beta has finished");
Console.ReadKey();
return 0;
}
两个带下划线的陈述都给出了相同的结果......有些可以解释 new Thread(something)和new Thread(new ThreadStart(something))
推荐答案
请参阅文档:MSDN ThreadStart委托 [ ^ ]
It说:
See the documentation: MSDN ThreadStart Delegate[^]
It says:
"Visual Basic and C# users can omit the ThreadStart or ParameterizedThreadStart delegate constructor when creating a thread. In Visual Basic, use the AddressOf operator when passing your method to the Thread constructor; for example, Dim t As New Thread(AddressOf ThreadProc). In C#, simply specify the name of the thread procedure. The compiler selects the correct delegate constructor."
基本上,您根本不需要使用ThreadStart,因为编译器会为您排序并自动使用相应的委托。
Basically, you don''t need to use the ThreadStart at all as the compiler sorts it out for you and uses the appropriate delegate automatically.
这篇关于差异b / w Thread和ThreadStart的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!