C#锁线程
类似于unity碰撞事件,A对象同时触发B、C对象的事件,B、C事件同时调用A方法的问题
public class Person { public delegate void ValueChangeDel(); public event ValueChangeDel valueChangeEvent; public void Triger() { valueChangeEvent(); } } public partial class Form1 : Form { Person p1 = new Person(); Person p2 = new Person(); public Form1() { InitializeComponent(); } string txt = null; public int value; static object _object = new object(); private bool isChange = false; public void Methord() { lock (_object)//锁代码块 { if (!isChange) { value = -value; txt += value + "\r\n"; isChange = true; } else { isChange = false; } } } private void Form1_Load(object sender, EventArgs e) { p1.valueChangeEvent += new Person.ValueChangeDel(Methord); p2.valueChangeEvent += new Person.ValueChangeDel(Methord); } private void numericUpDown1_ValueChanged(object sender, EventArgs e) { if (numericUpDown1.Value == 2) { value = (int)numericUpDown1.Value; new Thread(() => { p1.Triger(); }).Start(); new Thread(() => { p2.Triger(); }).Start(); } if (numericUpDown1.Value == 4) { richTextBox1.Text = txt; } } }