1.ConcurrentDictionary
ConcurrentDictionary 并发字典,保证多线程情况下的安全性
Dictionary 非线程安全集合
using System.Collections.Concurrent;
class Program { static void Main(string[] args) { ConcurrentDictionary<string, Student> students = new ConcurrentDictionary<string, Student>(); ConcurrentDictionary<string, Teacher> teachers = new ConcurrentDictionary<string, Teacher>(); // 添加键值对 students.TryAdd("刘一凡", new Student {Grade=1 ,Sex=Sex.Male,Age = 10}); teachers.TryAdd("顾老师", new Teacher {TeachSubject="语文",Sex = Sex.Female,Age=45 }); ////查询顾老师的信息 if (teachers.TryGetValue("顾老师", out var teacher)) { Console.WriteLine($"顾老师教授科目为:{teacher.TeachSubject}"); Console.WriteLine($"顾老师年龄为:{teacher.Age}"); } if (students.TryGetValue("刘一凡", out var student)) { Console.WriteLine($"刘一凡所在年级为:{student.Grade}"); Console.WriteLine($"刘一凡性别为:{student.Sex}"); } } }
enum Sex { Male, Female } internal class People { private int age; /// <summary> /// 年龄 /// </summary> public int Age { get { return age; } set { age = value; } } private Sex sex; /// <summary> /// 性别 /// </summary> public Sex Sex { get { return sex; } set { sex = value; } } }
internal class Student:People { private int grade; /// <summary> /// 年级 /// </summary> public int Grade { get { return grade; } set { grade = value; } } } internal class Teacher : People { private string teachSubject; /// <summary> /// 教授科目 /// </summary> public string TeachSubject { get { return teachSubject; } set { teachSubject = value; } } }
2.ManualResetEvent
表示必须手动重置信号的线程同步事件。 无法继承此类。
public sealed class ManualResetEvent : System.Threading.EventWaitHandle
static ManualResetEvent mre = new ManualResetEvent(false); static void Main(string[] args) { Thread th = new Thread(new ThreadStart(()=> { Thread.Sleep(1000); Console.WriteLine("Async Time =" + DateTime.Now.ToString("hh:mm:ss fff")); Thread.Sleep(5000); mre.Set(); })); th.Start(); Console.WriteLine("Start Time =" + DateTime.Now.ToString("hh:mm:ss fff")); mre.Reset(); bool isback = mre.WaitOne(); Console.WriteLine($"IsBack = {isback}"); Console.WriteLine("End Time =" + DateTime.Now.ToString("hh:mm:ss fff")); Console.Read(); }
3.wpf“调用线程无法访问此对象,因为另一个线程拥有该对象。
this.Dispatcher.Invoke(new Action(delegate
{
}));
4.Windows Presentation Foundation (WPF) 项目中不支持 Application
重新添加引用:PresentationCore PresentationFramework WindowsBase
标签:Console,C#,Sex,ConcurrentDictionary,杂记,WriteLine,new,随笔,public From: https://www.cnblogs.com/echo-efun/p/18346843