c#控制台多线程入门代码

发布时间:2019-11-04编辑:脚本学堂
分享一段c#多线程代码,c#控制台下测试多线程的,学习下c#操作多线程的方法与技巧,一个c#多线程编程的入门例子。

c#控制台下多线程操作代码

例子:
 

复制代码 代码示例:
class Program
{
static void Main(string[] args)
{
 ThreadStart num = new ThreadStart(PrintNum);
 Thread ConstrolNum = new Thread(num);
 ThreadStart str = new ThreadStart(PrintStr);
 Thread ConstrolStr = new Thread(str);
 Stopwatch watch = new Stopwatch();
 watch.Start();
 ConstrolNum.Start();
 ConstrolStr.Start();
 while (true)
 {
if (ConstrolNum.ThreadState == System.Threading.ThreadState.Stopped && ConstrolStr.ThreadState == System.Threading.ThreadState.Stopped)
{
 watch.Stop();
 Console.WriteLine(watch.Elapsed.TotalMilliseconds);
 break;
}
 }
 Console.ReadKey();
}
private static void PrintNum()
{
 for (int i = 1; i < 1000; i++)
 {
Console.WriteLine(i);
 }
}
private static void PrintStr()
{
 for (int i = 1; i < 1000; i++)
 {
Console.WriteLine("当前数为:{0}", i);
 }
}
}