class Program
{
class TestEnqueue
{
static Queue<string> str = new Queue<string>();
public static void AddEnqueue()
{
for (int i = 0; i < 10; i++)
{
string s= i.ToString();
Console.WriteLine("Task1 now runing");
str.Enqueue(s);
}
}
public static void DelEnqueue()
{
for (int i = 0; i < 10; i++)
{
// string s = i.ToString();
string s= str.Dequeue();
Console.WriteLine("Task2 now runing::::"+ s);
}
}
}
static void Main(string[] args)
{
Task t1 = new Task(TestEnqueue.AddEnqueue);
t1.Start();
Task t2 = new Task(TestEnqueue.DelEnqueue);
t2.Start();
Console.ReadKey();
}
}
}
t2在队列为空的时候报错。
![](https://www.codeprj.com/image/aHR0cHM6Ly9pbWFnZXMyMDE1LmNuYmxvZ3MuY29tL2Jsb2cvOTM0NDg0LzIwMTYxMi85MzQ0ODQtMjAxNjEyMjMwMDMxMTYwNTctNjk4NTQ2NjUzLnBuZw==.png)
有报错时候是这样
![](https://www.codeprj.com/image/aHR0cHM6Ly9pbWFnZXMyMDE1LmNuYmxvZ3MuY29tL2Jsb2cvOTM0NDg0LzIwMTYxMi85MzQ0ODQtMjAxNjEyMjMwMDMzMzY3OTItMTk2MzE2NTUwLnBuZw==.png)
好像还是没法测出两个task同时一个在写,然后一个在读。几乎同时运行的效果。
另外程序报错之后出错地str 实际是10个数的,为何有数还报错,可能是报错延缓吧,t2报错时,t1还在往里写数据,等错显示出来之后,t1运行完了。不知能否这么理解
![](https://www.codeprj.com/image/aHR0cHM6Ly9pbWFnZXMyMDE1LmNuYmxvZ3MuY29tL2Jsb2cvOTM0NDg0LzIwMTYxMi85MzQ0ODQtMjAxNjEyMjMwMDM5MjAxODItMTY5MTc0NDMyOC5wbmc=.png)
加一行代码
Task t2 = new Task(TestEnqueue.DelEnqueue); t1.Start(); t2.Wait(); t2.Start();
![](https://www.codeprj.com/image/aHR0cHM6Ly9pbWFnZXMyMDE1LmNuYmxvZ3MuY29tL2Jsb2cvOTM0NDg0LzIwMTYxMi85MzQ0ODQtMjAxNjEyMjMwMDQyMjY1NDItNTY5Mzk3MDI3LnBuZw==.png)
启动 Task() 时效
Stopwatch sw = new Stopwatch(); sw.Start(); Task t = new Task(MakeResult); t.Start(); sw.Stop(); Debug.WriteLine(" 触发时间ms:"+sw.Elapsed.TotalMilliseconds); ;
第一次启动20毫秒。第二次开始变低
![](https://www.codeprj.com/image/aHR0cHM6Ly9pbWFnZXMyMDE1LmNuYmxvZ3MuY29tL2Jsb2cvOTM0NDg0LzIwMTYxMi85MzQ0ODQtMjAxNjEyMjMwOTQwMzI5MDEtMTUyMzYxMzMyMy5wbmc=.png)
|