首页 > 学院 > 开发设计 > 正文

C#线程安全、事件、元组的使用

2019-11-08 02:41:33
字体:
来源:转载
供稿:网友
using System;using System.Collections.Generic;using System.Linq;using System.Reflection;using System.Text;using System.Threading.Tasks;using System.Threading;using System.Collections;using System.Collections.Concurrent;namespace Consoleapplication7{    class PRogram    {        static int count = 0;        static void Main(string[] args)        {            //线程安全            ConcurrentQueue<Teacher> queue = new ConcurrentQueue<Teacher>();            var j = 0;            Task.Factory.StartNew(() =>            {                while (true)                {                    queue.Enqueue(new Teacher { Name = "李雪-A-" + j++ });                    Thread.Sleep(100);                }            });            var m = 0;            Task.Factory.StartNew(() =>            {                while (true)                {                    queue.Enqueue(new Teacher { Name = "李雪-B-" + m++ });                    Thread.Sleep(100);                }            });            Task.Factory.StartNew(() =>            {                while (true)                {                    Teacher p_teacher;                    queue.TryDequeue(out p_teacher);                    if (p_teacher != null)                        Console.WriteLine(p_teacher.Name);                    Thread.Sleep(TimeSpan.FromSeconds(1));                }            });            Parallel.ForEach(new int[] { 1, 2, 3 }, (p) =>            {                count++;                Console.WriteLine("处理结果:" + count);                System.Threading.Thread.Sleep(TimeSpan.FromSeconds(2));            });            Console.WriteLine(count);            Console.WriteLine(Assembly.GetEntryAssembly().CodeBase);            Console.WriteLine(typeof(Teacher).FullName);            Teacher teacher = (Teacher)Assembly.LoadFile(System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "ConsoleApplication7.exe")).CreateInstance(typeof(Teacher).FullName);            Student student = new Student();            student.Listen(teacher);            teacher.Say("同学生们好!");            Tuple<string, int, double> studentScore = Tuple.Create("肖", 1, 100.1);            Console.WriteLine(studentScore.Item1);            Console.ReadKey();        }    }    public class Student    {        private Teacher teacher;        public void Listen(Teacher teacher)        {            this.teacher = teacher;            this.teacher.SayEvent += Teacher_SayEvent;        }        private void Teacher_SayEvent(object sender, string e)        {            Console.WriteLine("老师我听到您说:" + e);        }    }    public class Teacher    {        public string Name { get; set; }        public event EventHandler<string> SayEvent;        public void Say(string msg)        {            Console.WriteLine("老师说:" + msg);            SayEvent(this, msg);        }    }}
上一篇:poj 3461

下一篇:hdu 2600排序

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表