[英]Threading concept in C#
我是C#的新手,还在学习线程概念。 我写了一个程序如下
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
namespace ConsoleApplication17
{
class Program
{
static void Main(string[] args)
{
System.Threading.ThreadStart th1 = new System.Threading.ThreadStart(prnt);
Thread th = new Thread(th1);
th.Start();
bool t = th.IsAlive;
for (int i = 0; i < 10; i++)
{
Console.WriteLine(i + "A");
}
}
private static void prnt()
{
for (int i = 0; i < 10; i ++)
{
Console.WriteLine(i + "B");
}
}
}
}
我期待输出如下: -
1A
2A
1B
3A
2B...
因为我相信主线程和新创建的线程都应该同时执行。
但是输出是有序的,首先调用prnt
函数,然后执行Main
方法for循环。
也许一个10的cicle不足以看到两个线程同时运行。 使用更长的循环或在循环迭代中放置Thread.Sleep(100)。 启动一个线程非常昂贵。 可能的情况是,由于线程启动所需的时间,您在线程循环开始之前执行主循环
我同意您之前需要添加Thread.Sleep(几秒* 1000)的答案
我建议你阅读这篇关于线程的文章https://msdn.microsoft.com/ru-ru/library/system.threading.thread(v=vs.110).aspx
static void Main(string[] args)
{
Thread th = new Thread(prnt);
th.Start();
for (int i = 0; i < 10; i++)
{
//sleep one second
Thread.Sleep(1000);
Console.WriteLine(i + "A");
}
//join the basic thread and 'th' thread
th.Join();
}
private static void prnt()
{
for (int i = 0; i < 10; i++)
{
//sleep one second
Thread.Sleep(1000);
Console.WriteLine(i + "B");
}
}
更新 :进程用于隔离在该进程的上下文中运行的应用程序和线程。
通过这种方式,操作系统可以更轻松地管理不同的应用程序,管理崩溃和上下文切换(提供给每个应用程序的时间段由CPU执行)。 背后的想法是在预定义的时间段内运行线程,当应用程序运行所允许的时间结束时,CPU切换到要执行的其他线程。
将Threading类用于应用程序中的小型异步任务。
请参阅以下示例中的内容,您可以使用System.Threading命名空间创建新线程。 注意如何调用t.Join()来等待新线程完成。
请注意,Spleep(1)将强制更改上下文,这就是与您相关的示例。 尝试将其更改回零并查看结果。
using System;
using System.Threading;
namespace Chapter1
{
public static class Threads1
{
public static void ThreadMethod()
{
for (int i = 0; i < 10; i++)
{
Console.WriteLine("ThreadProc: {0}", i);
Thread.Sleep(1);
}
}
public static void Main(string[] args)
{
Thread t = new Thread(new ThreadStart(ThreadMethod));
t.Start();
for (int i = 0; i < 4; i++)
{
Console.WriteLine("Main thread: Do some work.");
Thread.Sleep(1);
}
t.Join();
Console.Read();
}
}
}
// OUTPUT:
//Main thread: Do some work.
//ThreadProc: 0
//ThreadProc: 1
//Main thread: Do some work.
//ThreadProc: 2
//Main thread: Do some work.
//ThreadProc: 3
//Main thread: Do some work.
//ThreadProc: 4
//ThreadProc: 5
//ThreadProc: 6
//ThreadProc: 7
//ThreadProc: 8
//ThreadProc: 9
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.